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

public class PlayerController : MonoBehaviour
{
    public string[] MoveUpKeys;
    public string[] MoveDownKeys;
    public GameController GameController;

    private bool PlayerDead = false;

    private void Update()
    {
        bool moveup = false;
        bool movedown = false;

        foreach (string s in MoveUpKeys)
            if (Input.GetKey(s))
                moveup = true;

        foreach (string s in MoveDownKeys)
            if (Input.GetKey(s))
                movedown = true;

        float movement = 0;
        if (moveup) movement += 0.1f;
        if (movedown) movement -= 0.1f;

        movement += this.transform.position.y;
        movement = Mathf.Clamp(movement, -8.5f, 8.5f);

        transform.position = new Vector3(-17.14f, movement, 0);
    }

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag != "PowerUp" && !PlayerDead)
            StartCoroutine(PlayerDied());
        else
        {
            collision.GetComponent<MeshRenderer>().enabled = false;
            GameController.Score++;
            GameController.UI.transform.Find("Score").GetComponent<UnityEngine.UI.Text>().text = "Score: " + GameController.Score;
        }
    }

    private IEnumerator PlayerDied()
    {
        foreach (MeshRenderer lFlyPart in GetComponentsInChildren<MeshRenderer>())
            lFlyPart.enabled = false;
        GameController.UI.transform.Find("Score").GetComponent<UnityEngine.UI.Text>().fontSize = 32;
        if (GameController.FirstPerson)
            GameController.UI.transform.Find("Score").GetComponent<RectTransform>().localPosition = new Vector3(400, 130, 0);
        PlayerDead = true;
        GetComponent<Collider>().enabled = false;
        GameController.UI.GetComponent<AudioSource>().Stop();
        GetComponent<AudioSource>().Play();
        transform.Find("Fly").GetComponent<AudioSource>().Stop();

        if (GameController.FirstPerson)
            PlayerPrefs.SetString("FirstPersonTopScore", GameController.Score.ToString());
        else
            PlayerPrefs.SetString("ThirdPersonTopScore", GameController.Score.ToString());

        yield return new WaitForSeconds(3f);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}