using Myra.Graphics2D.Brushes;
using Myra.Graphics2D.UI;
using Sledgemapper.Messages;
using System;
using System.Threading.Tasks;
using TinyMessenger;

namespace Sledgemapper.UI
{
    public partial class CampaignList
    {
        private CommunicationManager CommunicationManager { get; }
        private TinyMessengerHub Messenger { get; }
        
        private bool _campaignSelected;

        public CampaignList(CommunicationManager communicationManager, TinyMessengerHub messenger)
        {
            BuildUI();
            CommunicationManager = communicationManager;
            Messenger = messenger;

            BtnNewCampaign.Click += (s, e) =>
            {
                OnMenuCampaignNew(s, e);
                this.GetContainingWindow().Close();
            };

            BtnLoadCampaign.Click += (s, e) =>
            {
                if (_campaignSelected)
                {
                    _campaignSelected = false;
                    Messenger.Publish(new CampaignSelectedMessage(this));
                    this.GetContainingWindow().Close();
                }
            };

            BtnCancelCampaign.Click += (s, e) =>
            {
                this.GetContainingWindow().Close();
            };
        }

        private void OnMenuCampaignNew(object sender, EventArgs e)
        {
            if (sender is MenuItem { Enabled: false })
            {
                return;
            }

            new CampaignWindow(CommunicationManager, Messenger).ShowInModalWindow(Desktop, "New campaign");
        }

        private void OnCampaignSelected(object sender, EventArgs e)
        {
            var item = sender as ListItem;

            State.Instance.CampaignName = item.ItemName.Text;
            State.Instance.CampaignId = (Guid)item.Tag;
            var list = item.Parent as Grid;
            for (var i = 0; i < list.ChildrenCount; i++)
            {
                if (list.GetChild(i) is HorizontalStackPanel currentItem) currentItem.Background = new SolidBrush("#D9D9D9FF");
            }
            item.Background = new SolidBrush(Settings.Instance.OverlayTintColor);
            _campaignSelected = true;
        }

        public async Task<bool> LoadCampaigns()
        {
            var campaigns = await CommunicationManager.GetCampaigns();

            if (campaigns is null)
            {
                
                return false;
            }

            foreach (var campaign in campaigns)
            {
                var item = new ListItem
                {
                    ItemName =
                    {
                        Text = campaign.Name
                    },
                    Tag = campaign.Id
                };
                item.TouchUp += OnCampaignSelected;
                StackCampaignsList.AddChild(item);
            }

            return true;
        }
    }
}