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

public class TreeProcessor : MonoBehaviour {
    private static List<Tree> Trees = new List<Tree>();
    public static void AddTree(Tree a)
    {
        Trees.Add(a);
        a.Destroyed += A_Destroyed;
    }

    private static void A_Destroyed(object sender, System.EventArgs e)
    {
        Trees.Remove(sender as Tree);
    }

    public static Tree FindClosestSelectedTreeTo(Vector3 point)
    {
        Tree closest = null;
        float sqrDist = 0.0f;

        foreach(Tree candidate in Trees.Where<Tree>(tree => tree.SelectedAsTractorTarget))
        {
            if (closest == null || (candidate.transform.position - point).sqrMagnitude < sqrDist)
            {
                closest = candidate;
                sqrDist = (candidate.transform.position - point).sqrMagnitude;
            }
        }

        return closest;
    }

    public TextMeshProUGUI PercentTreesDestroyedText = null;
    
    public GameObject FireFX = null;
    public GameObject SmokeFX = null;

    public Material BurningLeaves = null;
    public Material NormalLeaves = null;
    public Material CharcoalMaterial = null;

    public bool firstTime = true;

    void DrawFirstMinimap()
    {
        Minimap mm = GetComponent<Minimap>();
        foreach (Tree t in Trees)
        {
            mm.DrawTree(t);            
        }
    }

    public int TreesDestroyed = 0;

    public int TotalTrees
    {
        get { return Trees.Count;  }
    }
    public int BurningTrees = 100;
    public float PercentTreesDestroyed
    {
        get { return (float)TreesDestroyed / (float)Trees.Count; }
    }

    // Update is called once per frame
    void Update () {
        if (firstTime)
        {
            DrawFirstMinimap();
            firstTime = false;
        }

        BurningTrees = 0;
        foreach(Tree t in Trees)
        {
            Combustible c = t.GetComponent<Combustible>();
            if (t.SelectedAsTractorTarget && t.burningState != BurnState.Waiting)
            {
                t.SetSelectedAsTractorTarget(false);
            }

            if (t.ShowingSuppression && !c.IsSuppressed)
            {
                // Hide suppression
                t.transform.Find("Retardant").GetComponent<MeshRenderer>().enabled = false;
                t.ShowingSuppression = false;
            }
            if (!t.ShowingSuppression && c.IsSuppressed)
            {
                // Show suppression
                t.transform.Find("Retardant").GetComponent<MeshRenderer>().enabled = true;
                t.ShowingSuppression = true;
            }

            if (t.burningState == BurnState.Waiting && c.CurrentTemperature > c.CombustionTemperature * 0.01f)
            {
                t.burningState = BurnState.Smoking;
                if (t.AttachedParticleEffect != null)
                    Destroy(t.AttachedParticleEffect);
                t.AttachedParticleEffect = GameObject.Instantiate(SmokeFX, t.transform);
            }
            if (t.burningState != BurnState.Burning && c.IsBurning)
            {
                t.burningState = BurnState.Burning;
                GetComponent<Minimap>().DrawTree(t);

                if (t.AttachedParticleEffect != null)
                    Destroy(t.AttachedParticleEffect);
                t.AttachedParticleEffect = GameObject.Instantiate(FireFX, t.transform);

                
                // Swap out to burning leaves color
                t.transform.Find("Trunk").Find("Leaves").GetComponent<MeshRenderer>().material = BurningLeaves;

            }
            if (t.burningState == BurnState.Smoking && c.CurrentTemperature < Mathf.Epsilon)
            {
                // If a tree was smoking but the temperature has since dropped back to 0 then remove the smoke
                if (t.AttachedParticleEffect != null)
                    Destroy(t.AttachedParticleEffect);

                t.burningState = BurnState.Waiting;
            }

            if (t.burningState == BurnState.Burning)
            {
                BurningTrees++;
            }

            if (t.burningState == BurnState.Burning && !c.IsBurning)
            {
                // Transition OUT of burning state - we cooled down for some reason - probably water
                t.burningState = BurnState.Waiting;
                GetComponent<Minimap>().DrawTree(t);

                if (t.AttachedParticleEffect != null)
                    Destroy(t.AttachedParticleEffect);

                // Turn leaves back to normal
                t.transform.Find("Trunk").Find("Leaves").GetComponent<MeshRenderer>().material = NormalLeaves;

            }

            if (t.burningState == BurnState.Burning && c.Fuel < Mathf.Epsilon)
            {
                c.Fuel = 0.0f;
                c.CurrentTemperature = 0.0f;
                t.burningState = BurnState.Smothered;
                GetComponent<Minimap>().DrawTree(t);

                if (t.AttachedParticleEffect != null)
                {
                    t.AttachedParticleEffect.GetComponent<ParticleSystem>().Stop();
                    Destroy(t.AttachedParticleEffect, 5.0f);
                }

                // Swap out to smothered tree model
                t.transform.Find("Trunk").Find("Leaves").gameObject.SetActive(false);
                t.transform.Find("Trunk").GetComponent<MeshRenderer>().material = CharcoalMaterial;

                TreesDestroyed++;
            }
        }


        PercentTreesDestroyedText.text = PercentTreesDestroyed.ToString("P0");

    }
}
