using BarRaider.SdTools;
using BarRaider.SdTools.Wrappers;
using ClipTrimDotNet.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClipTrimDotNet.Keys
{
    public class DataSourceItem
    {
        public string label { get; set; } = "";
        public string value { get; set; } = "";
    }
    [PluginActionId("com.michal-courson.cliptrim.profile-switcher")]
    public class ProfileSwitcher : KeypadBase
    {
        private class PluginSettings
        {
            public static PluginSettings CreateDefaultSettings()
            {
                PluginSettings instance = new PluginSettings();
                instance.ProfileName = null;
                return instance;
            }

            [JsonProperty(PropertyName = "profileName")]
            public string? ProfileName { get; set; }
        }

        #region Private Members

        private PluginSettings settings;

        #endregion
        public ProfileSwitcher(SDConnection connection, InitialPayload payload) : base(connection, payload)
        {
            if (payload.Settings == null || payload.Settings.Count == 0)
            {
                settings = PluginSettings.CreateDefaultSettings();
                SaveSettings();
            }
            else
            {
                settings = payload.Settings.ToObject<PluginSettings>()!;
            }
            Logger.Instance.LogMessage(TracingLevel.INFO, $"ProfileSwitcher initialized with payload {JsonConvert.SerializeObject(payload)}");
            GlobalSettingsManager.Instance.RequestGlobalSettings();
            Connection.OnSendToPlugin += Connection_OnSendToPlugin;
            SetTitle();
        }

        private async void SetTitle()
        {

            await Connection.SetTitleAsync(settings.ProfileName);
        }

        private async void Connection_OnSendToPlugin(object? sender, SDEventReceivedEventArgs<BarRaider.SdTools.Events.SendToPlugin> e)
        {
            //Logger.Instance.LogMessage(TracingLevel.INFO, "get profiles");
            if (e.Event.Payload["event"] is null) return;

            if (e.Event.Payload["event"]!.ToString() == "getProfiles")
            {
                var files = ClipTrimClient.Instance.GetCollectionNames();
                var items = files.Select(x => new DataSourceItem { label = x, value = x});
                var obj = new JObject
                {
                    ["event"] = "getProfiles",
                    ["items"] = JArray.FromObject(items)
                };
                await Connection.SendToPropertyInspectorAsync(obj);
            }
            
        }


        public override void Dispose()
        {
        }

        public override async void KeyPressed(KeyPayload payload)
        {
            GlobalSettings.Instance.SetCurrentProfile(settings.ProfileName??"");
            ClipTrimClient.Instance.PageMode = false;
            PageNavigator.TickAll();

            await Connection.SetGlobalSettingsAsync(JObject.FromObject(GlobalSettings.Instance));
            await Connection.SwitchProfileAsync("ClipTrim");
        }

        public override void KeyReleased(KeyPayload payload)
        {

        }

        public override void OnTick()
        {
            SetTitle();
        }

        public override void ReceivedSettings(ReceivedSettingsPayload payload)
        {
            //Logger.Instance.LogMessage(TracingLevel.INFO, $"ProfileSwitcher received settings {JsonConvert.SerializeObject(payload.Settings)}");
            Tools.AutoPopulateSettings(settings, payload.Settings);
            SaveSettings();
        }

        public override void ReceivedGlobalSettings(ReceivedGlobalSettingsPayload payload)
        {
            Tools.AutoPopulateSettings(GlobalSettings.Instance, payload.Settings);
            ClipTrimClient.Instance.CheckPort();
            //if (payload.Settings == null || payload.Settings.Count == 0)
            //{
            //    var inst = GlobalSettings.Instance;
            //}
            //else
            //{
            //    GlobalSettings.Instance = payload.Settings.ToObject<GlobalSettings>();
            //}
        }

        #region Private Methods

        private Task SaveSettings()
        {
            return Connection.SetSettingsAsync(JObject.FromObject(settings));
        }

        #endregion
    }
}