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

public class MovableManager : MonoBehaviour
{
    [SerializeField] private GameObject movablePrefab;
    [SerializeField] private MovableHolder movableHolderPrefab;
    [SerializeField] private GridLayoutGroup gridLayoutGroup;
    [SerializeField] private int groupCountLimit;
    private List<IMovable> _movables = new List<IMovable>();
    private List<MovableHolder> _movableHolders = new List<MovableHolder>();
    public EShapeType shapeType;

    public virtual void Start()
    {
        CreateMovables(new EnumData<EMovableType>("123456"));
    }
    public virtual void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            ResetMovables();
        }
    }
    private void ResetMovables()
    {
        for (int i = 0; i < _movables.Count; i++)
        {
            IMovable movable = _movables[i];
            movable.Destroy();
        }
        _movables.Clear();
        for (int i = 0; i < _movableHolders.Count; i++)
        {
            MovableHolder movableParent = _movableHolders[i];
            Destroy(movableParent.gameObject);
        }
        _movableHolders.Clear();
        Start();
    }
    internal virtual void CreateMovables(EnumData<EMovableType> movableTypeData)
    {
        List<EMovableType> movableTypes = movableTypeData.DecodeData<EMovableType>();
        gridLayoutGroup.enabled = false;
        for (int i = 0; i < movableTypes.Count; i++)
        {
            MovableHolder movableHolder = Instantiate(movableHolderPrefab, gridLayoutGroup.transform);
            _movableHolders.Add(movableHolder);
            GameObject movableObject = Instantiate(movablePrefab, movableHolder.transform);
            IMovable movable = movableObject.GetComponent<IMovable>();
            movableHolder.SetHoldingMovable(movable);
            movable.Init(movableTypes[i], movableHolder);
            _movables.Add(movable);
        }
        gridLayoutGroup.enabled = true;
    }
    private void RemoveMovable(IMovable movable)
    {
        _movables.Remove(movable);
    }

    private void OnMovablePlaced(IMovable movable)
    {
        RemoveMovable(movable);
    }
    private void OnMovableMouseUp(IMovable movable)
    {
    }
    private void OnEnable()
    {
        App_EventManager.OnMovablePlaced += OnMovablePlaced;
        App_EventManager.OnMovableMouseUp += OnMovableMouseUp;
    }
    private void OnDisable()
    {
        App_EventManager.OnMovablePlaced -= OnMovablePlaced;
        App_EventManager.OnMovableMouseUp -= OnMovableMouseUp;
    }
}
