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

public class HouseController : MonoBehaviour
{
    [SerializeField] private Renderer houseRenderer;
    [SerializeField] private GameObject checkmark;
    [SerializeField] private GameObject xmark;

    public bool HasElectricity { get { return houseRenderer.material.color != Color.green; } }
    public bool IsVisible { get { return houseRenderer.isVisible; } }
    public Bounds SpriteBounds { get { return houseRenderer.bounds; } }

    private Coroutine GetAngryCor;
    private float maxTime;
    private float counter = 0;
    private bool beyondRepair = false;
    private bool Connected = false;

    void Awake()
    {
        //houseRenderer = GetComponent<Renderer>();
        maxTime = GameManager.Instance.TimeToGetAngry;
        GetAngryCor = StartCoroutine(GettingAngry());
        xmark.SetActive(false);
        HouseOutOfRegion();
    }

    public void HouseInTempRegion()
    {
        if (Connected)
            return;

        checkmark.SetActive(true);
    }

    public void HouseOutOfRegion()
    {
        if (Connected)
            return;

        checkmark.SetActive(false);
    }

    public void PaintHouse()
    {
        if (beyondRepair)
            return;

        StartCoroutine(WaitFrameToPaintHouse());
    }

    IEnumerator WaitFrameToPaintHouse()
    {
        while(houseRenderer == null)
        {
            yield return null;
        }

        if (GetAngryCor != null)
        {
            StopCoroutine(GetAngryCor);
        }

        houseRenderer.material.color = Color.green;
    }

    public void ClearHouse()
    {
        //print(this.gameObject.name + ": " + Connected + "; " + beyondRepair);
        if (Connected || beyondRepair)
            return;

        houseRenderer.material.color = Color.white;
        if (GetAngryCor != null)
        {
            StopCoroutine(GetAngryCor);
        }
        GetAngryCor = StartCoroutine(GettingAngry());
    }

    private IEnumerator GettingAngry()
    {
        counter = 0;
        while(counter < maxTime && !GameManager.Instance.GameIsOver)
        {
            yield return null;
            houseRenderer.material.color = Color.Lerp(Color.white, Color.red, counter / maxTime);
            counter += Time.deltaTime;
        }

        if (GameManager.Instance.GameIsOver)
            yield break;

        GameManager.Instance.HouseGotAngry();
        xmark.SetActive(true);
        beyondRepair = true;
    }

    public void SetConnected()
    {
        checkmark.SetActive(false);
        GameManager.Instance.HousePositioned();

        Connected = true;
        PaintHouse();
    }
}
