using UnityEngine;
using System.Collections;
using System;

public class StealableObject : MonoBehaviour
{

	public bool stolen = false;

	void Start()
	{
		GameMgr.instance.registerStealable(this);
	}
	
	void Update()
	{
	
	}

    void OnTriggerEnter2D(Collider2D other)
    {
        StartCoroutine(Steal(other));
    }

    private IEnumerator Steal(Collider2D other)
    {
        yield return new WaitForSeconds(1.0f);
        GameMgr.instance.stealObject(this);
		if(GameMgr.instance.stealables.Count != 0 && Array.TrueForAll(GameMgr.instance.stealables.ToArray(), value => {return value.stolen == true; }))
		{
			GameMgr.instance.toWin("player1Win");
		}
        else
        {
            GameObject temple = GameObject.Find("Temple");
            Monk[] monks = temple.GetComponentsInChildren<Monk>();
            Vector3 collisionPosition = other.transform.position;
            Array.Sort(monks, delegate (Monk monk1, Monk monk2) {
                float whosClosest = (monk1.transform.position - collisionPosition).magnitude - (monk2.transform.position - collisionPosition).magnitude;
                if (whosClosest == 0)
                {
                    return 0;
                }
                return (whosClosest < 0 ? -1 : +1);
            });
            SoundManager.PlaySfx(SoundManager.Sfx.sfx_error);
            int i = 0;
            for (; i < GameMgr.instance.culpritsPerTheft; i++)
            {                
                monks[i].GetComponentInChildren<SuspicionMarker>().DelayedMark(true);
            }
            for (; i < monks.Length; i++)
            {
                monks[i].GetComponentInChildren<SuspicionMarker>().DelayedMark(false);
            }

        }
		gameObject.SetActive(false);        
    }

    /*
    private IEnumerator MarkSuspects(Monk[] monks)
    {
        yield return new WaitForSeconds(0.5f);
        SoundManager.PlaySfx(SoundManager.Sfx.sfx_error);
        for (int i = 0; i < GameMgr.instance.culpritsPerTheft; i++)
        {
            monks[i].GetComponentInChildren<SuspicionMarker>().enabled = true;
        }        
    }
    */
}
