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

public class Soccermagnet : MonoBehaviour
{
    Soccerman owner;
    bool hasEnemy = false;
    bool hasBall = false;
    bool magnetEnabled = true;

    List<Collider> enemiesInTrigger = new List<Collider>();
    Vector3 dirToBall;

    Collider myCollider;
    float radius;
    float pullPercent;

	// Use this for initialization
	void Start ()
    {
        owner = transform.parent.GetComponent<Soccerman>();
        myCollider = GetComponent<Collider>();

        transform.localScale = Vector3.one * owner.pullRange;
        radius = owner.pullRange / 2;
	}
	
	void FixedUpdate()
    {
        if (hasEnemy || !magnetEnabled) return;

        if(hasBall)
        {
            //dirToBall = (Ball.instance.transform.position - transform.position).normalized;
            dirToBall = (transform.position - Ball.instance.transform.position).normalized;
            //pullPercent = 1 - (Vector3.Distance(Ball.instance.transform.position, transform.position) / radius);
            Ball.instance.AddMagnetForce(dirToBall * 1.0f /** pullPercent*/);
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Player")
        {
            Soccerman s = other.GetComponent<Soccerman>();
            if (s != owner)
            {
                hasEnemy = true;
                AddObject(other);
            }
        }

        if(other.tag == "Ball")
        {
            hasBall = true;
            owner.hasBall = true;

            Ball.instance.AddPlayer(myCollider);
            Ball.instance.RefreshMaterial();
        }
    }

    void OnTriggerExit(Collider other)
    {
        if(other.tag == "Player")
        {
            RemoveObject(other);
            hasEnemy = enemiesInTrigger.Count > 0;
        }

        if (other.tag == "Ball")
        {
            hasBall = false;
            owner.hasBall = false;

            Ball.instance.RemovePlayer(myCollider);
            Ball.instance.RefreshMaterial();
        }
    }

    void AddObject(Collider c)
    {
        if (!enemiesInTrigger.Contains(c))
            enemiesInTrigger.Add(c);
    }

    void RemoveObject(Collider c)
    {
        if (enemiesInTrigger.Contains(c))
            enemiesInTrigger.Remove(c);
    }

    public void SetMagnetEnabled(bool isEnabled) { magnetEnabled = isEnabled; }
}
