using Managers;
using Offers;
using System.Collections;
using System.Collections.Generic;
using UI.EmailWindow;
using UnityEngine;

namespace UI
{
    public class OfferWindowController : MonoBehaviour
    {
        [SerializeField] GameObject acceptedPrefab;
        [SerializeField] GameObject completedPrefab;
        [SerializeField] Transform cellsContainer;

        List<OfferCellController> acceptedPool = new List<OfferCellController>();
        List<OfferCellController> completedPool = new List<OfferCellController>();

        private void OnEnable() => UpdateOrders();

        public void UpdateOrders()
        {
            acceptedPool.ForEach(x => x.gameObject.SetActive(false));

            var activeOrders = GameManager.Instance.GetAcceptedOffers();

            int poolSize = acceptedPool.Count;

            for (int i = 0; i < activeOrders.Count; i++)
            {
                OfferCellController orderCell = null;

                if (poolSize > i)
                {
                    orderCell = acceptedPool[i];
                    orderCell.gameObject.SetActive(true);
                }
                else
                {
                    orderCell = Instantiate(acceptedPrefab, cellsContainer).GetComponent<OfferCellController>();
                    acceptedPool.Add(orderCell);
                }

                var orderInfo = activeOrders[i];

                orderCell.SetData(orderInfo);
                orderInfo.SubscribeOnCompleted(UpdateOrders);

                orderCell.transform.SetSiblingIndex(i);
            }

            completedPool.ForEach(x => x.gameObject.SetActive(false));

            var completedOrders = GameManager.Instance.GetCompletedOffers();

            poolSize = completedPool.Count;

            for (int i = 0; i < completedOrders.Count; i++)
            {
                OfferCellController orderCell = null;

                if (poolSize > i)
                {
                    orderCell = completedPool[i];
                    orderCell.gameObject.SetActive(true);
                }
                else
                {
                    orderCell = Instantiate(completedPrefab, cellsContainer).GetComponent<OfferCellController>();
                    completedPool.Add(orderCell);
                }

                var orderInfo = completedOrders[i];

                orderCell.SetData(orderInfo);
                orderCell.transform.SetSiblingIndex(i + activeOrders.Count);
            }
        }

        private void OnDisable()
        {
            var activeOrders = GameManager.Instance.GetAcceptedOffers();
            activeOrders.ForEach(x => x.UnSubscribeOnCompleted(UpdateOrders));
        }
    }
}