using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Item : MonoBehaviour {

    public enum ItemType { Heavy, Light }
    public ItemType type;

    public float slowSpeed = 5f;
    public float fastSpeed = 10f;

    public float minimalPlayerProximity = 2f;

    private List<GameObject> playersConneted = new List<GameObject>();
    private MotherShip motherShip;
    private NavMeshAgent agent;

    private Vector3 dir;

    private bool placed = false;

    void Start() {
        motherShip = FindObjectOfType<GameManager>().GetMotherShip().GetComponent<MotherShip>();
        agent = GetComponent<NavMeshAgent>();
    }

    void Update() {
        switch (type) {
            case ItemType.Heavy:
                if (playersConneted.Count == 2)
                    MoveTowardsMotherShip(slowSpeed);
                break;
            case ItemType.Light:
                if (playersConneted.Count == 1)
                    MoveTowardsMotherShip(slowSpeed);
                else if (playersConneted.Count == 2)
                    MoveTowardsMotherShip(fastSpeed);
                break;
            default:
                break;
        }

        CheckMotherShipProximity();

        for (int i = playersConneted.Count - 1; i >= 0; i--) {
            if (playersConneted[i].GetComponent<Player>().IsAlive() == false)
                playersConneted.RemoveAt(i);
        }
    }

    void CheckMotherShipProximity() {
        if (!placed && Vector3.Distance(transform.position, motherShip.transform.position) < motherShip.GetRepairDistance()) {
            motherShip.PlaceItem((type == ItemType.Heavy ? 2 : 1));
            placed = true;
            Remove();
            Debug.Log("Placing");
        }
    }

    void Remove() {
        this.enabled = false;
        Destroy(gameObject);
    }

    void MoveTowardsMotherShip(float speed) {
        dir = motherShip.transform.position - transform.position;
        dir.Normalize();
        dir *= speed;

        agent.SetDestination(transform.position + dir);
    }

    void OnTriggerEnter(Collider collider) {
        if (collider.transform.tag == "Player" && !playersConneted.Contains(collider.gameObject)) {
            playersConneted.Add(collider.gameObject);
            Debug.Log("Adding player");
        }
    }

    void OnTriggerExit(Collider collider) {
        if (collider.transform.tag == "Player" && playersConneted.Contains(collider.gameObject))
            playersConneted.Remove(collider.gameObject);
            Debug.Log("Remove player");
    }
}