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

public class PlayerControllerScript : MonoBehaviour {

    public float health;
    public bool invincible;

    bool interact;

    public int playerState;
    public int roomNum;

    public Switches switchScript;

    [SerializeField]
    float movementSpeed = 1f;

    float horizontal;
    float vertical;

    public GameObject player;

    Vector3 startPos;

    public GameObject camera;

    public GameObject hitBoxPrefab;

    Rigidbody2D rb2d;
    Animator anim;
    SpriteRenderer sRenderer;


    // Use this for initialization
    void Start () { 
        playerState = 0;
        startPos = this.transform.position;
        rb2d = player.GetComponent<Rigidbody2D>();
        anim = player.GetComponent<Animator>();
        sRenderer = player.GetComponent<SpriteRenderer>();
        anim.SetInteger("AnimCheck", 1);
        interact = false;
    }

    private void Update()
    {
        if (horizontal > 0 || horizontal < 0)
        {
            anim.SetBool("Horizontal", true);
        }
        else
        {
            anim.SetBool("Horizontal", false);
        }
        if(horizontal > 0)
        {
            anim.SetBool("Right", true);
            if (playerState == 0 || playerState == 2 || playerState == 4)
            {
                sRenderer.flipX = false;
            }
        }
        else
        {
            anim.SetBool("Right", false);
        }
        if (horizontal < 0)
        {
            anim.SetBool("Left", true);
            if (playerState == 0 || playerState == 2 || playerState == 4)
            {
                sRenderer.flipX = true;
            }
        }
        else
        {
            anim.SetBool("Left", false);
        }

        if (vertical < 0)
        {
            anim.SetBool("Down", true);
        }
        else
        {
            anim.SetBool("Down", false);
        }

        if(Input.GetButton("Fire1"))
        {
            //hitBox.SetActive(true);
            GameObject hitbox = (GameObject)Instantiate(hitBoxPrefab, transform.position, Quaternion.identity);
            hitbox.transform.position = transform.position;
            float angle = (Mathf.Atan2(-horizontal, vertical)) * Mathf.Rad2Deg;
            hitbox.transform.localRotation = Quaternion.AngleAxis(angle, Vector3.forward);
            hitbox.name = "Hitbox";
            anim.SetBool("Attack", true);
            //Destroy(GameObject.Find("Hitbox"));
            StartCoroutine(DestroyHitbox());
        }

        if (Input.GetButtonDown("Fire2"))
            interact = true;
        else if (Input.GetButtonUp("Fire2"))
            interact = false;

    }

    // Update is called once per frame
    void FixedUpdate () {
        horizontal = Input.GetAxisRaw("Horizontal");
        vertical = Input.GetAxisRaw("Vertical");

        float angle = (Mathf.Atan2(-horizontal, vertical)) * Mathf.Rad2Deg;

        Vector2 playerMoveDir = new Vector2(horizontal, vertical);

        rb2d.velocity = playerMoveDir * movementSpeed;

        //hitBox.transform.localRotation = Quaternion.AngleAxis(angle, Vector3.forward);

        //Vector3 playerMoveDir = Vector3(horizontal, vertical, 0);
        //player.transform.position += playerMoveDir * movementSpeed;

    }

    void UpdatePlayerSpeed()
    {
        switch(playerState)
        {
            case 0:
                movementSpeed = 1f;
                break;
            case 1:
                movementSpeed = 2f;
                break;
            case 2:
                movementSpeed = 3f;
                break;
            case 3:
                movementSpeed = 4f;
                break;
            case 4:
                movementSpeed = 5f;
                break;
        }
    }

    public void TakeDamage(float damage)
    {
        health -= damage;
        FindObjectOfType<AudioManagerScript>().PlayClip("PlayerDamage");
        StartCoroutine(InvincibleTimer());
    }

    IEnumerator InvincibleTimer()
    {
        invincible = true;
        yield return new WaitForSeconds(3);
        invincible = false;
    }

    void OnTriggerEnter2D(Collider2D coll)
    {
        string trigName = coll.gameObject.name;
        Vector3 pos = new Vector3();

        switch (trigName)
        {
            case "Trans 1":
                if (roomNum == 1)
                {
                    pos = GameObject.Find("Room 2").transform.position;
                    roomNum = 2;
                }
                else
                {
                    pos = GameObject.Find("Room 1").transform.position;
                    roomNum = 1;
                }
                StartCoroutine(Lerp(camera, pos, 2));
                    break;
            case "Trans 2":
                if (roomNum == 2)
                {
                    pos = GameObject.Find("Room 3").transform.position;
                    roomNum = 3;
                }
                else
                {
                    pos = GameObject.Find("Room 2").transform.position;
                    roomNum = 2;
                }
                StartCoroutine(Lerp(camera, pos, 2));
                break;
            case "Trans 3":
                if (roomNum == 2)
                {
                    pos = GameObject.Find("Room 4").transform.position;
                    roomNum = 4;
                }
                else if(roomNum==4)
                {
                    pos = GameObject.Find("Room 2").transform.position;
                    roomNum = 2;
                }
                StartCoroutine(Lerp(camera, pos, 2));
                break;
            case "Trans 4":
                if (roomNum == 4)
                {
                    pos = GameObject.Find("Room 5").transform.position;
                    roomNum = 5;
                }
                else
                {
                    pos = GameObject.Find("Room 4").transform.position;
                    roomNum =4;
                }
                StartCoroutine(Lerp(camera, pos, 2));
                break;
            case "Trans 5":
                if (roomNum == 5)
                {
                    pos = GameObject.Find("Room 6").transform.position;
                    roomNum = 6;
                }
                else
                {
                    pos = GameObject.Find("Room 5").transform.position;
                    roomNum = 5;
                }
                StartCoroutine(Lerp(camera, pos, 2));
                break;
        }

        if (coll.gameObject.tag == "bodypart")
        {
            Destroy(coll.gameObject);
            FindObjectOfType<AudioManagerScript>().PlayClip("LimbPickup");
            StartCoroutine(BodyPickup());
            
        }

        if (coll.gameObject.tag == "Head" && playerState == 4)
        {
            Destroy(coll.gameObject);
            FindObjectOfType<AudioManagerScript>().PlayClip("LevelComplete");
            Debug.Log("Win");
            SceneManager.LoadScene("Win");

        }

        


    }

    void OnTriggerStay2D(Collider2D coll)
    {
        print(interact);
        if ((coll.gameObject.tag == "Switch") && (interact))
        {

            if (coll.gameObject.name == "Lever 1")
                switchScript.UseDoor(0);
            else if (coll.gameObject.name == "Lever 2")
                switchScript.UseDoor(1);
            else if (coll.gameObject.name == "Lever 3")
                switchScript.UseDoor(2);
        }
    }

    IEnumerator BodyPickup()
    {
        playerState++;
        anim.SetInteger("Player State", playerState);
        yield return new WaitForSeconds(1);
        anim.SetInteger("AnimCheck", playerState + 1);
        UpdatePlayerSpeed();
    }
    IEnumerator Lerp(GameObject lerpObject, Vector3 finalPos, float timeTaken)
    {
        float currentTime = 0;

        while (currentTime < timeTaken)
        {
            currentTime += Time.deltaTime;
            lerpObject.transform.position =
                Vector3.Lerp(lerpObject.transform.position, finalPos, currentTime / timeTaken);
            yield return 0;
        }
    }

    IEnumerator DestroyHitbox()
    {
        
        yield return new WaitForSeconds(0.01f);
        Destroy(GameObject.Find("Hitbox"));
        anim.SetBool("Attack", false);
        //hitBox.GetComponent<PlayerAttackScript>().killEnemy = false;
        //hitBox.SetActive(false);
    }
}
