using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class PuzzleManager : MonoBehaviour
{
    public static PuzzleManager Instance { get; private set; }
    [SerializeField] ScreenShake m_shaker;
    [SerializeField] EndSpot[] m_endSpots;
    [SerializeField] UFOMove m_ufo;
    int m_moveCount = 0;

    [SerializeField] Rect m_bounds;
    [SerializeField] TextMeshProUGUI m_moveCountTxt;
    [SerializeField] TextMeshProUGUI m_clearText;
    [SerializeField] AnimationCurve m_clearCurve;
    [SerializeField] string m_nextScene;


    private void Awake()
    {
        if(Instance == null)
        {
            Instance = this;
        }
        else
        {
            return;
        }
    }

    private void Start()
    {
        m_ufo.SetMoveRect(m_bounds);
        m_moveCountTxt.text = m_moveCount.ToString("000");
        m_clearText.gameObject.SetActive(false);
    }

    public void OnCowDrop()
    {
        m_shaker.Shake(0.5f, 0.1f);

        bool success = true;
        for(int i=0; i< m_endSpots.Length; i++)
        {
            if(!m_endSpots[i].CheckEndSpot())
            {
                success = false;
            }
        }

        if(success)
        {
            PuzzleComplete();
        }
    }

    public void OnMove()
    {
        m_moveCount++;
        m_moveCountTxt.text = m_moveCount.ToString("000");
    }

    void PuzzleComplete()
    {
        Debug.Log("YOU WIN!");
        m_ufo.enabled = false;
        StartCoroutine(TextAppear());
    }

    IEnumerator TextAppear()
    {
        m_clearText.gameObject.SetActive(true);
        m_clearText.transform.localScale = Vector3.zero;

        float t = 0;
        while(t < 1)
        {
            t = Mathf.MoveTowards(t, 1, Time.deltaTime * 1.5f);
            m_clearText.transform.localScale = Vector3.one * m_clearCurve.Evaluate(t);

            yield return null;
        }

        yield return new WaitForSeconds(3);
        GetComponent<SceneChanger>().GotoScene(m_nextScene);
    }
}
