using BarRaider.SdTools;
using BarRaider.SdTools.Wrappers;
using ClipTrimDotNet.Client;
using System.Text.Json.Serialization;
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
{
    [PluginActionId("com.michal-courson.cliptrim.player")]
    public class Player : KeypadBase
    {

        private int coordIndex;
        private string? current_text = null;
        private KeyCoordinates coordinates;

        static List<Player> instances = new();

        public Player(SDConnection connection, InitialPayload payload) : base(connection, payload)
        {
            coordinates = payload.Coordinates;
            GlobalSettingsManager.Instance.RequestGlobalSettings();
            instances.Add(this);
            coordIndex = Math.Max((coordinates.Row - 1) * 5 + coordinates.Column, 0);
            OnTick();
        }

        public static void TickAll()
        {
            Logger.Instance.LogMessage(TracingLevel.INFO, "Ticking all Player instances" + instances.Count);
            foreach (var instance in instances)
            {
                instance.OnTick();
            }
            instances.RemoveAll(i => i == null);
        }

        private async void CheckFile()
        {
            var next_text = ClipTrimClient.Instance.GetPlayerStringByCoordinateIndex(coordIndex);
            if(next_text != current_text)
            {
                current_text = next_text;
                await Connection.SetTitleAsync($"{current_text ?? ""}");
            }
            current_text = next_text;
        }

        public override void Dispose()
        {
        }

        public override void KeyPressed(KeyPayload payload)
        {
            ClipTrimClient.Instance.PlayClip(coordIndex);
        }


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


        public override void ReceivedGlobalSettings(ReceivedGlobalSettingsPayload payload) {
            Tools.AutoPopulateSettings(GlobalSettings.Instance, payload.Settings);
        }

        public override void KeyReleased(KeyPayload payload)
        {
            
        }

        public override void ReceivedSettings(ReceivedSettingsPayload payload)
        {

        }

    }
}