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

public class Player : MonoBehaviour
{
    private SpriteRenderer spriteRenderer;
    private Transformation characterTransform;

    private PlayerSO playerSprites;


    void Start()
    {
        Init();
    }

    private void Init()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        characterTransform = Transformation.Jekyll;
        playerSprites = Array.Find(GameManager.Instance.PlayerStats, x => x.CharacterTransform == characterTransform);
        spriteRenderer.sprite = NewSprite(CharacterMood.Normal);
    }

    private void OnEnable()
    {
        EventManager.Instance.onTransformation += CharacterTransformation;
        EventManager.Instance.StartTick();
    }

    private void OnDisable()
    {
        if(EventManager.Instance != null)
        {
            EventManager.Instance.onTransformation -= CharacterTransformation;
            EventManager.Instance.CancelTick();
        }
    }

    private void CharacterTransformation(Transformation form)
    {
        Debug.Log("form: " + form);
        Debug.Log("form: " + characterTransform);

        if(form == Transformation.Hyde && characterTransform == Transformation.Hyde)
        {
            EventManager.Instance.GameOver();
            Debug.Log("Game Over");
            SceneManager.LoadScene("LoseScene");

        }

        characterTransform = form;
        playerSprites = Array.Find(GameManager.Instance.PlayerStats , x => x.CharacterTransform == form);
        ChangeMood(CharacterMood.Pain);
    }

    private void ChangeMood(CharacterMood mood)
    {
        StartCoroutine(MoodTimer(mood));
    }

    IEnumerator MoodTimer(CharacterMood mood)
    {
        spriteRenderer.sprite = NewSprite(mood);
        yield return new WaitForSeconds(2);
        spriteRenderer.sprite = NewSprite(CharacterMood.Normal);
    }

    private Sprite NewSprite(CharacterMood mood)
    {
        return Array.Find(playerSprites.PlayerMoods, x => x.Mood == mood).MoodSprite;
    }

}
