using UnityEngine;
using System.Collections;

public class GameScript : MonoBehaviour {

    public GameObject player;

    [HideInInspector]
    public GameObject player1;
    [HideInInspector]
    public GameObject player2;

    private int dead = 0;

    // Use this for initialization
    void Start () {
        // create player
        player1 = Instantiate(player, new Vector3(-5, 0, 0), Quaternion.identity) as GameObject;
        player1.GetComponent<PlayerScript>().id = 1;
        player1.GetComponent<PlayerVisuals>().randomizeColors(1);
        player2 = Instantiate(player, new Vector3(5, 0, 0), Quaternion.identity) as GameObject;
        player2.GetComponent<PlayerScript>().id = 2;
        player2.GetComponent<PlayerVisuals>().randomizeColors(2);
    }
	
	// Update is called once per frame
	void LateUpdate () {
        float realPos;
        float origin = 0;
        if (dead == 0)
        {
            realPos = player1.transform.position.x - player2.transform.position.x;
            origin = (player1.transform.position.x < player2.transform.position.x) ?
            player1.transform.position.x :
            player2.transform.position.x;
        } else if ( dead == 1)
        {
            realPos = player2.transform.position.x;
            origin = realPos;
        }
        else
        {
            realPos = player1.transform.position.x;
            origin = realPos;
        }
        float distance = Mathf.Abs(realPos);
        float newScale = ((distance + 5) / Screen.width * Screen.height / 2.0f);
        if (newScale < 4.0f) newScale = 4.0f;
        if(Camera.main.orthographicSize != newScale)
        {
            Camera.main.orthographicSize = Camera.main.orthographicSize - (Camera.main.orthographicSize-newScale) * Time.deltaTime * 2;
        }
        Vector3 newPos = new Vector3(origin + (distance / 2), GetComponent<Camera>().transform.position.y, -4);
        if (Camera.main.transform.position != newPos)
        {
            Camera.main.transform.position = Camera.main.transform.position - (Camera.main.transform.position - newPos) * Time.deltaTime * 3;
        }
        
    }

    public void KillAndRespawn(GameObject ob)
    {
        ob.SetActive(false);
        dead = ob.GetComponent<PlayerScript>().id;
        StartCoroutine(ActivateRoutine(3.0f, ob));
    }
    
    private IEnumerator ActivateRoutine(float time, GameObject gameObject)
    {
        yield return new WaitForSeconds(time);
        if (gameObject.Equals(player1))
        {
            gameObject.transform.position = new Vector3(player2.transform.position.x - 15, 0, 0);
            player1.GetComponent<PlayerVisuals>().randomizeColors(1);
        }
        else
        {
            gameObject.transform.position = new Vector3(player1.transform.position.x + 15, 0, 0);
            player2.GetComponent<PlayerVisuals>().randomizeColors(2);
        }
        gameObject.SetActive(true);
        dead = 0;
    }

}
