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

public class Supply : Nodo
{
    public Color colorThisSupply;

    bool canSpawnNutrient = false;
    bool canSpawnNextNutrient = true;
    public float timeForNextNutrient = 2f;

    public GameObject perfabNutrient;
    public Transform[] entries;
    float distanceToDetectArround = 0.2f;
    public Nodo[] objectsArround;
    public SpriteRenderer supplyRenderer;

    TailSupplyManager m_TailManager;

    GameObject[] nutList;

    LevelController m_LevelController;

    public ParticleSystem RootConnected_particlesystem;

    void Start()
    {
        m_LevelController = GameObject.FindGameObjectWithTag("LevelController").GetComponent<LevelController>();
        m_Collider2D = GetComponent<Collider2D>();
        m_TailManager = GetComponent<TailSupplyManager>();
        nutList = new GameObject[1];
        objectsArround = new Nodo[4];
        GetArroundZones();
        entriesType = new GridTypes[4];
        SetTypesEntries();
        SetColor();
    }
    void SetColor()
    {
        supplyRenderer.color = colorThisSupply;
        UpdateGraphics();
    }

    private void SetTypesEntries()
    {
        entriesType[0] = GridTypes.Empty;
        entriesType[1] = GridTypes.Empty;
        entriesType[2] = GridTypes.Empty;
        entriesType[3] = GridTypes.Empty;

        if (objectsArround[0] != null)
        {
            if (objectsArround[0].gameObject.tag == ("Plant"))
            {
                PutRoot(0);
            }
        }
    }

    private void GetArroundZones()
    {
        m_Collider2D.enabled = false;
        RaycastHit2D _hit0;
        RaycastHit2D _hit1;
        RaycastHit2D _hit2;
        RaycastHit2D _hit3;
        _hit0 = Physics2D.Raycast(entries[0].position, new Vector2(0f, 1f), distanceToDetectArround);
        if (_hit0.collider != null)
        {
            objectsArround[0] = _hit0.collider.GetComponent<Nodo>();
        }
        else
        {
            objectsArround[0] = null;
        }
        _hit1 = Physics2D.Raycast(entries[1].position, new Vector2(-1f, 0f), distanceToDetectArround);
        if (_hit1.collider != null)
        {
            objectsArround[1] = _hit1.collider.GetComponent<Nodo>();
        }
        else
        {
            objectsArround[1] = null;
        }
        _hit2 = Physics2D.Raycast(entries[2].position, new Vector2(0f, -1f), distanceToDetectArround);
        if (_hit2.collider != null)
        {
            objectsArround[2] = _hit2.collider.GetComponent<Nodo>();
        }
        else
        {
            objectsArround[2] = null;
        }
        _hit3 = Physics2D.Raycast(entries[3].position, new Vector2(1f, 0f), distanceToDetectArround);
        if (_hit3.collider != null)
        {
            objectsArround[3] = _hit3.collider.GetComponent<Nodo>();
        }
        else
        {
            objectsArround[3] = null;
        }
        m_Collider2D.enabled = true;
    }
    void OnMouseDown()
    {
        if (Manager.Instance.StillPlaying() && CanPutRoot())
        {
            TryPutRoot();
        }
    }

    private bool CanPutRoot()
    {
        if (m_LevelController.numRoot < m_LevelController.maxRoot)
        {
            if (m_Parent != null) return false;
            return true;
        }
        else { return false; }
    }

    private void TryPutRoot()
    {
        for (int i = 0; i < 4; i++)
        {
            if (objectsArround[i] != null)
            {
                if (objectsArround[i] == Manager.Instance.lastRootSelected && TryAttachColor(Manager.Instance.lastRootSelected.m_PlantsController))
                {
                    PutRoot(i);
                    return;
                }
            }
        }
    }

    private bool TryAttachColor(PlantsController _PlantsController)
    {
        if (_PlantsController.needsSatisfied) return false;
        return _PlantsController.IAcceptMoreSupply(colorThisSupply);
    }

    public override void RemoveRoot(bool first)
    {
        m_LevelController.numRoot--;
        entriesType[0] = GridTypes.Empty;
        entriesType[1] = GridTypes.Empty;
        entriesType[2] = GridTypes.Empty;
        entriesType[3] = GridTypes.Empty;
        UpdateGraphics();
        m_PlantsController.RemovedSupply(colorThisSupply);
        m_PlantsController = null;
        m_Parent.OnRemove -= RemoveRoot;
        m_Parent = null;
        m_WhereIsParent = 0;
    }
    public void UpdateGraphics()
    {
        m_TailManager.SetTileSprite();
    }

    private void PutRoot(int idx)
    {
        m_LevelController.numRoot++;
        m_Parent = objectsArround[idx].GetComponent<Nodo>();
        entriesType[idx] = GridTypes.Parent;
        m_WhereIsParent = idx;
        m_PlantsController = m_Parent.m_PlantsController;
        m_Parent.entriesType[(idx + 2) % 4] = GridTypes.Son;
        UpdateGraphics();
        if (m_Parent is CuadradoRaices) (m_Parent as CuadradoRaices).UpdateGraphics();
        m_PlantsController.SupplyReached(colorThisSupply);
        m_Parent.OnRemove += RemoveRoot;

        for(int i = 0; i<objectsArround.Length; i++)
        {
            Vector3 newRot = RootConnected_particlesystem.transform.eulerAngles;
            switch (m_WhereIsParent)
            {
                case 0:
                    RootConnected_particlesystem.transform.eulerAngles = new Vector3(newRot.x, newRot.y,90);
                    break;                                                                     
                case 1:                                                                        
                    RootConnected_particlesystem.transform.eulerAngles = new Vector3(newRot.x, newRot.y,180);
                    break;                                                                     
                case 2:                                                                        
                    RootConnected_particlesystem.transform.eulerAngles = new Vector3(newRot.x, newRot.y,270);
                    break;                                                                    
                case 3:                                                                        
                    RootConnected_particlesystem.transform.eulerAngles = new Vector3(newRot.x, newRot.y,0);
                    break;
            }
        }

        FMODUnity.RuntimeManager.PlayOneShot("event:/Plant/Plant_connected");
        RootConnected_particlesystem.Play();
        RootConnected_particlesystem.GetComponent<ChangeParticleColour>().setColors(colorThisSupply, colorThisSupply, 0.5f);
    }

    void Update()
    {
        if (m_Parent != null)
        {
            canSpawnNutrient = true;
        }
        else
        {
            canSpawnNutrient = false;
            if (nutList[0] != null)
            {
                Destroy(nutList[0]);
            }
        }


        if (canSpawnNutrient && (Manager.Instance.GetCanStartGeneringAliments() || m_PlantsController.m_Lvl > 0))
        {
            if (CanSpawnNutrient())
            {
                nutList[0] = Instantiate(perfabNutrient, transform.position, Quaternion.identity);
                nutList[0].GetComponent<AlimentController>().SetNutrient(m_Parent.gameObject, colorThisSupply);
            }
        }


    }

    private bool CanSpawnNutrient()
    {
        if (nutList[0] == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    IEnumerator NextNutrient()
    {
        yield return new WaitForSeconds(timeForNextNutrient);
        canSpawnNutrient = true;
    }
}

