using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PickupItem : NetworkBehaviour
{
    public PickupType type;
    public float radius=1;
    public Color gizmoColor = Color.green;
    public bool active = true;
    
    
    void Update()
    {
        if(!isServer){return;}
        if(!active){return;}

        Collider2D hit = Physics2D.OverlapCircle(transform.position, radius);
        if(hit!=null && hit.GetComponent<SpaceshipController>()!=null){
//            Debug.Log(hit.GetComponent<SpaceshipController>().pname +$" collected me at {transform.position}");
            hit.GetComponent<SpaceshipController>().CollectPickup(type);
            active=false;
            Deactivate();
        }
    }

    public void Reposition(Vector3 newPosition){
        if(isServer){
            reposition(newPosition);

            RpcReposition(newPosition);
        }else{
            CmdReposition(newPosition);
        }
    }

    [Command]
    void CmdReposition(Vector3 newPosition){
        reposition(newPosition);

        RpcReposition(newPosition);
    }

    [ClientRpc]
    void RpcReposition(Vector3 newPosition){
        reposition(newPosition);   
    }

    void reposition(Vector3 newPosition){
        active=true;
        transform.position = newPosition;
        gameObject.SetActive(true);
    }

    public void Deactivate(){
        if(isServer){
            deactivate();
            RpcDeactivate();
        }else{
            CmdDeactivate();
        }
    }

    void deactivate(){
        active=false;
        gameObject.SetActive(false);
        SceneData.GameManager.DeactivatePickupItem(this);
    }

    [Command]
    void CmdDeactivate(){
        deactivate();
        RpcDeactivate();
    }

    [ClientRpc]
    void RpcDeactivate(){
        deactivate();
    }

     private void OnDrawGizmos() {
        Gizmos.color = gizmoColor;
        Gizmos.DrawWireSphere(transform.position,radius);
    }

    public enum PickupType{
        Star,
        Moon
    }
}

