using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utils;

public class ComboCenter : Singleton<ComboCenter> {
    public delegate void HugeComboHandler();

    public event HugeComboHandler HugeComboHandlers;

    public AudioClip claps;


    public float degradationTick = 2f;
    public float maximumComboThing = 5f;
    public float comboIncrement = 0.5f;

    private float comboAccumulation;

    float combolevel;
    float totalscore;
    void Awake()
    {
        StartCoroutine(ComboDegrador());
    }

    public void IncreaseComboLevel(float by)
    {

        //print(combolevel);
        //print(by);
        float newCombo = Mathf.Clamp(combolevel+by, 1f, maximumComboThing);

        float realIncrement = Mathf.Max(newCombo - combolevel, 0);

        comboAccumulation += realIncrement;
        //combolevel += by;

        combolevel = newCombo;

        //print("why");
        //print(comboAccumulation);
        if (comboAccumulation > 0.7f)
        {
            //print("dsdf");
            ReportCombos();
            comboAccumulation = 0;
        }
    }

    public string GetCombo()
    { 
    
        return string.Format("{0:0.0}", combolevel);
    }

    public float GetComboRatio()
    {
        return (combolevel - 1) / (maximumComboThing - 1);
    }

    public void IncreaseScoreBy(float score)
    {
        totalscore += score * combolevel;
    }

    public string GetScore()
    {
        return string.Format("{0:0}", totalscore);
    }

    void ReportCombos()
    {
        if (!GetComponent<AudioSource>().isPlaying)
            GetComponent<AudioSource>().PlayOneShot(claps);

        System.Delegate[] dels = HugeComboHandlers.GetInvocationList();
        foreach(HugeComboHandler s in dels)
        {
            if (s != null)
            {
                s.Invoke();
            }
            else
            {
                HugeComboHandlers -= s;
            }
        }
    }

    IEnumerator ComboDegrador()
    {
        yield return new WaitForSeconds(degradationTick);
        if (combolevel > 1)
        {
            combolevel -= comboIncrement;
        }
        if (combolevel < 1) combolevel = 1;

        comboAccumulation -= 3*comboIncrement;
        if (comboAccumulation < 0) comboAccumulation = 0;

        StartCoroutine(ComboDegrador());
    }

    void OnGUI() {
        /*GUIStyle guiStyle = new GUIStyle(); 
        guiStyle.fontSize = 40;
        GUI.Label(new Rect(50, 50, 100, 100), combolevel.ToString(), guiStyle);
        GUI.Label(new Rect(50, 100, 100, 100), totalscore.ToString(), guiStyle);*/
    }

}
