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

public class LevelManager : MonoBehaviour
{
    public GameObject MainMenu;
    public GameObject MenuCredits;
    public Slider sliderPaura;
    public Slider sliderTorcia;
    public GameObject torcia;
    public Animator bambinaAnimator;


    float currentFear = 0.0f;
    public float fearPerSecond = 5.0f;
    public float fearDropAmount = 2.0f;
    public float maxFear = 20.0f;
    public bool canMove = true;

    float sliderTime = 1.0f; // For having a smooth slider transition
    float fearSliderLastUpdate = 0.0f;
    float chargeSliderLastUpdate = 0.0f;

    public bool isInLight = true; //wether the player is in a light area

    // Flashlight management
    public float autoRechargeTime = 3.0f;
    public float dischargePerSecond = 0.5f;
    public float dischargeRate = 0.10f;
    public float chargeAmountAuto = 0.05f;
    public float chargeAmountKeypress = 0.05f;
    bool isRecharging = false;
    public float currentCharge;
    public float maxCharge = 5.0f;
    public bool hasToRecharge = false;


    //QTE
    public bool duringQTE = false;
    public KeyCode QTEbuttonToPress = KeyCode.A;
    public bool QTEbuttonPressed = false;
    public float QTEfearGain = 5.0f;
    public float scaredTime = 2.0f;


    // Input management
    bool isFireKeptDown = false;


	InputToPress inputToPress;

	public void ChangeScenes(string name)
    {
        SceneManager.LoadScene(name);
    }

    public void Start()
    {
		inputToPress = FindObjectOfType<InputToPress>();

		// Start fear rising
		exitLightArea();
        currentCharge = maxCharge;

    }

    public void Update()
    {
        updateFearSlider();
        checkWinOrLose();
        if (hasToRecharge)
        {
            if (Input.GetAxis("Jump") > 0 && !isFireKeptDown)
            {
                isFireKeptDown = true;
                if (!isInLight)
                {
                    manualRechargeOneStep();
                }
            }
            else if (Input.GetAxis("Jump") == 0)
            {
                isFireKeptDown = false;
            }
        }

        if (duringQTE)
        {
            if (Input.GetKeyDown(QTEbuttonToPress))
            {
                QTEbuttonPressed = true;
                QTESucceded();
            }
        }

    }

    // Events
    public void enterLightArea(bool firstTime)
    {
        isInLight = true;
        stopRaisingFear();
        if (firstTime)
        {
            // If the player enters the light spot for the first time we give her a bonus
            lowerFear();
        }

        // Stop discharging the flashlight and start autorecharge
        CancelInvoke("discharge");
        startAutoRecharging();

    }

    public void exitLightArea()
    {
        isInLight = false;
        startRaisingFear();
        stopAutoRecharging();
        // begin discharging the light if it's on
        InvokeRepeating("discharge", 1.0f, 1.0f);
    }
    // Fear management
    public void startRaisingFear()
    {
        InvokeRepeating("raiseFear", 1.0f, 1.0f);
    }
    public void stopRaisingFear()
    {
        CancelInvoke("raiseFear");
    }
    public void raiseFear()
    {
        if (!isInLight && hasToRecharge)
        {
            currentFear = (currentFear <= maxFear - fearPerSecond) ? currentFear + fearPerSecond : maxFear;
            fearSliderLastUpdate = Time.time;
        }

    }
    public void lowerFear()
    {
        if (isInLight)
        {
            currentFear = (currentFear > 0) ? currentFear - fearDropAmount : 0;
            fearSliderLastUpdate = Time.time;
        }

    }

    int lastHeartbeat = -1;
    public void updateFearSlider()
    {
        //sliderPaura.value = currentFear / maxFear;
        sliderPaura.value = Mathf.Lerp(sliderPaura.value, currentFear / maxFear, Time.time - fearSliderLastUpdate);
        sliderTorcia.value = Mathf.Lerp(sliderTorcia.value, currentCharge / maxCharge, Time.time - chargeSliderLastUpdate);
        float relativeFear = currentFear / maxFear;

        int nextHeartbeat = -1;
        if (relativeFear >= 0 && relativeFear < 1.0f / 3.0f) {
            nextHeartbeat = 0;


        } else if (relativeFear >= 1.0f / 3.0f && relativeFear < 2.0f / 3.0f)
        {
            nextHeartbeat = 1;
        } else if (relativeFear >= 2.0f / 3.0f && relativeFear <= 1.0f)
        {
            nextHeartbeat = 2;
        }
        if (lastHeartbeat != nextHeartbeat)
        {
            SoundManager.sndManager.changeHeartBeat(nextHeartbeat);
            lastHeartbeat = nextHeartbeat;
        }
        
    }

    // Flashlight
    public void startAutoRecharging()
    {
        InvokeRepeating("autoRechargeOneStep", 0f, 0.2f);
        if (currentCharge > 0) { torcia.SetActive(true); }
    }

    public void stopAutoRecharging()
    {
        CancelInvoke("autoRechargeOneStep");
    }

    public void forceManualRecharge()
    {
        // Disable discharge of the torch, show button UI and prevent moving
        // TODO: Activate UI
        bambinaAnimator.SetBool("GoRun", false); // the character is still, so she cannot run
		inputToPress.Activate(KeyCode.Space);
        Debug.Log("You have to recharge!");
        CancelInvoke("discharge");
        hasToRecharge = true;
        bambinaAnimator.SetBool("Reload", true);
    }

    public void manualRechargeOneStep()
    {
        ///This function is called each time the player push the recharge button
        currentCharge = (currentCharge > maxCharge - chargeAmountKeypress) ? maxCharge : currentCharge + chargeAmountKeypress;
        chargeSliderLastUpdate = Time.time;
        if (currentCharge == maxCharge)
        {
            // We completely charged the flashlight
            hasToRecharge = false;
            torcia.SetActive(true);
            InvokeRepeating("discharge", 1.0f, 1.0f);
			inputToPress.Deactivate();
			bambinaAnimator.SetBool("Reload", false);
        }

    }


    public void discharge()
    {
        if (!isInLight && currentCharge > 0)
        {
            torcia.SetActive(true);
            currentCharge = (currentCharge > dischargePerSecond * dischargeRate) ? currentCharge - dischargePerSecond * dischargeRate : 0.0f;
            chargeSliderLastUpdate = Time.time;
        }
        else
        {
            // Turn off the flashlight and force to recharge
            torcia.SetActive(false);
            forceManualRecharge();
        }
    }

    public void autoRechargeOneStep()
    {
        currentCharge = (currentCharge > maxCharge - chargeAmountAuto) ? maxCharge : currentCharge + chargeAmountAuto;
        chargeSliderLastUpdate = Time.time;
        if (currentCharge == maxCharge)
        {
            stopAutoRecharging();
        }
    }


    public void beginQTE(EnterLight player, QTE source)
    {
        Debug.Log("An event begins!");
        // Stop fear gain and light discharge during the event
        CancelInvoke("discharge");
        CancelInvoke("raiseFear");
        duringQTE = true;
        this.QTEbuttonToPress = source.buttonToPress;
        QTEbuttonPressed = false;
        // turn the player torward the source
        Vector3 dest = new Vector3(source.transform.position.x, 0.0f, source.transform.position.z);
        player.gameObject.transform.LookAt(dest);
        bambinaAnimator.SetBool("GoRun", false);
        // start ui interface and timer
        Invoke("QTEfailed", source.maxTime);
        source.completed = true;

    }


    public void QTEfailed()
    {
        Debug.Log("Event failed!");
        duringQTE = false;
        // Gain a certain amount of fear
        currentFear = (currentFear <= maxFear - fearPerSecond) ? currentFear + fearPerSecond : maxFear;
        bambinaAnimator.SetTrigger("spaventata");
        Invoke("canMoveAgain", scaredTime);
        canMove = false;
        fearSliderLastUpdate = Time.time;
        if (!isInLight)
        {
            InvokeRepeating("discharge", 1.0f, 1.0f);
            InvokeRepeating("raiseFear", 1.0f, 1.0f);
        }


    }

    public void QTESucceded()
    {
        duringQTE = false;
        Debug.Log("Event succeded!");
        CancelInvoke("QTEfailed");
        if (!isInLight)
        {
            InvokeRepeating("discharge", 1.0f, 1.0f);
            InvokeRepeating("raiseFear", 1.0f, 1.0f);
        }

    }

    public void canMoveAgain()
    {
        canMove = true;
    }


    // Win/Lose condition
    public void checkWinOrLose()
    {
        if (currentFear >= maxFear)
        {
            // TODO: Activate lose screen
        }

    }


    //Main menu
    public void GoCreditsMainMenu()
    {
        MainMenu.SetActive(false);
        MenuCredits.SetActive(true);

    }

    public void ButtonBack()
    {
        MenuCredits.SetActive(false);
        MainMenu.SetActive(true);
    }


    public void QuitGame()
    {
        Application.Quit();
    }



}
