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


[System.Serializable]
public class TaskManager : MonoBehaviour
{
    public static TaskManager Instance;

    [SerializeField] public GameObject _panel_template;

    protected GameObject dynamicPanel;
    public bool isOpen = false;

    [Header("Tasks list")]
    [SerializeField] public List<Task> taskList;

    private void Awake()
    {
        if(Instance == null)
        {
            Instance = this;
      
        }else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            if (this._panel_template && !this.isOpen) 
            {
                this.OpenPanel();
            } else 
            {
                this.ClosePanel();
            }
        }
    }
    
     /// <summary>
     // Function which opne Task Panel if its close
     //
     // Create new Task Panel object instance on scene
     /// </summary>
    public void OpenPanel()
    {
        GameObject globalGUI =  GameObject.FindGameObjectsWithTag("GUI")[0];
        
        if(globalGUI)
        {
            this.dynamicPanel = Instantiate(_panel_template, _panel_template.transform.position, Quaternion.identity, globalGUI.transform);   // 4'th arg allow set object as child

            this.dynamicPanel.transform.localPosition = _panel_template.transform.position;   // prevent overwritten position by... environment???

            this.SetupPanel(); // bind pandel to current chest

            isOpen = true;
        } else {
            Debug.Log("Can't find global GUI object!!!");
        }

    }

     /// <summary>
     // Function which close Task Panel if its open
     /// </summary>
    public virtual void ClosePanel()
    {
        Destroy(dynamicPanel);
        isOpen = false;
    }

     /// <summary>
     // Function which allow to add new task to manager list of tasks
     //
     // Task Panel use this list during setup process 
     /// </summary>
    public void AddTask(Task _task)
    {
        taskList.Add(_task);
    }


    private void SetupPanel()
    {
        if(this.dynamicPanel)
        {
            this.dynamicPanel.GetComponent<TaskPanelController>().Setup(taskList);
        }
    }
}