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

namespace UI.EmailWindow
{
    public class EmailWindowController : MonoBehaviour
    {
        [SerializeField] OppenedMessageController messageController;
        [SerializeField] GameObject messageRowPrefab;
        [SerializeField] Transform messagesContainer;

        List<MessageRow> messagesRowsPool = new List<MessageRow>();

        private void OnEnable() => UpdateEmails();

        public void UpdateEmails()
        {
            messageController.gameObject.SetActive(false);

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

            var newOrders = GameManager.Instance.GetCreatedOffers();

            int messagesPoolSize = messagesRowsPool.Count;

            Offer firstOffer = null;

            for (int i = 0; i < newOrders.Count; i++)
            {
                MessageRow messageRow = null;

                if (messagesPoolSize > i)
                {
                    messageRow = messagesRowsPool[i];
                    messageRow.gameObject.SetActive(true);
                }
                else
                {
                    messageRow = Instantiate(messageRowPrefab, messagesContainer).GetComponent<MessageRow>();
                    messagesRowsPool.Add(messageRow);
                }

                var orderInfo = newOrders[i];

                messageRow.SetData(orderInfo, () => messageController.SetData(orderInfo));

                messageRow.transform.SetSiblingIndex(i);

                if (i == 0)
                    firstOffer = orderInfo;
            }

            if(firstOffer != null)
                messageController.SetData(firstOffer);
        }
    }
}