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

public class Player : MonoBehaviour
{
    public KeyCode lastKey;
    public Vector3 movementVector;
	public Vector3 activeVector;
    public bool holdingDown;
	public Collider2D otherCollider; 
	public string victoryScene;
	public GameObject restartImage;

    // Use this for initialization
    void Start()
    {
        InvokeRepeating("Move", 0f, 1f);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            movementVector = new Vector3(0f, 1f, 0f);
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            movementVector = new Vector3(0f, -1f, 0f);
        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            movementVector = new Vector3(-1f, 0f, 0f);
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            movementVector = new Vector3(1f, 0f, 0f);
        }

        if (holdingDown)
        {
            if (Input.GetKeyUp(KeyCode.UpArrow))
            {
                movementVector = new Vector3(0f, 0f, 0f);
                holdingDown = false;
            }
            else if (Input.GetKeyUp(KeyCode.DownArrow))
            {
                movementVector = new Vector3(0f, -0f, 0f);
                holdingDown = false;
            }
            else if (Input.GetKeyUp(KeyCode.LeftArrow))
            {
                movementVector = new Vector3(-0f, 0f, 0f);
                holdingDown = false;
            }
            else if (Input.GetKeyUp(KeyCode.RightArrow))
            {
                movementVector = new Vector3(0f, 0f, 0f);
                holdingDown = false;
            }
        }

    }


    void Move()
    {
		AttemptMove ();
		FinishMove ();

    }
    void AttemptMove()
    {
        if (Input.anyKey)
        {
            holdingDown = true;
        }
		activeVector = movementVector;


		transform.position += activeVector; //la wea
		checkCollider();
		if (otherCollider)
		{
			if (otherCollider.gameObject.tag == "Wall") 
			{
				transform.position -= activeVector;
				checkCollider ();
			}
			if (otherCollider.gameObject.tag == "Door") 
			{
				transform.position -= activeVector;
				checkCollider ();
			}
			if (otherCollider.gameObject.tag == "VictoryTile") 
			{
				SceneManager.LoadScene(victoryScene);
			}
			if (otherCollider.gameObject.tag == "Laser" || otherCollider.gameObject.tag == "Enemy") 
			{
				restartImage.GetComponent<SpriteRenderer>().enabled = true;
				Destroy (this);

			}
		}
    }
			
    
    void FinishMove()
    {
        if (!holdingDown)
        {
            movementVector = new Vector3(0f, 0f, 0f);
        }
    }
	void checkCollider()
	{
		otherCollider = Physics2D.OverlapCircle (new Vector2 (transform.position.x, transform.position.y), 0.2f);
	}

}
