/* Generated by MyraPad at 03/09/2021 17:13:57 */
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 MapList
    {
        private CommunicationManager CommunicationManager { get; }
        private TinyMessengerHub Messenger { get; }

        private string _selectedMap;
        private Guid _selectedMapId;
        public MapList(CommunicationManager communicationManager, TinyMessengerHub messenger)
        {
            CommunicationManager = communicationManager;
            Messenger = messenger;

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

            BtnLoadCampaign.Click += BtnLoadCampaign_Click;
        }

        private void BtnLoadCampaign_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(_selectedMap) && _selectedMapId!=Guid.Empty)
            {
                State.Instance.MapName = _selectedMap;
                State.Instance.MapId = _selectedMapId;
                Messenger.Publish(new MapOpenedMessage(this, _selectedMap, _selectedMapId));
                this.GetContainingWindow().Close();
            }
        }

        public async Task<bool> LoadMaps()
        {
            var campaigns = await CommunicationManager.GetMaps(State.Instance.CampaignId);
            if (campaigns is null)
            {
                return false;
            }

            foreach (var campaign in campaigns)
            {
                var item = new ListItem();
                item.ItemName.Text = campaign.SessionName;
                item.Tag = campaign.SessionId;
                item.TouchUp += OnMapSelected;
                StackCampaignsList.AddChild(item);
            }

            return true;
        }

        private void OnMapSelected(object sender, EventArgs e)
        {
            var item = sender as ListItem;
            var localContent = item.GetParentContentInWindow<Widget>();

            var list = item.Parent as Grid;
            for (var i = 0; i < list.ChildrenCount; i++)
            {
                var currentItem = list.GetChild(i) as HorizontalStackPanel;// UI.ListItem;
                currentItem.Background = new SolidBrush("#D9D9D9FF");
            }
            item.Background = new SolidBrush(Settings.Instance.OverlayTintColor);
            _selectedMap = item.ItemName.Text;
            _selectedMapId = (Guid)item.Tag;
        }

        private void OnMenuMapNew(object sender, EventArgs e)
        {
            new MapWindow(CommunicationManager, Messenger).ShowInModalWindow(Desktop, "New map");
        }
    }
}