using RobotLib.Communication;
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace RobotLib.SplitFlap
{
    public class DevSplitFlap : DevBase
    {
        private const string TOPIC_INITALL = "/splitFlap/cmd/init/";
        private const string TOPIC_CONFIGURE_SF = "/splitFlap/config/setup/";
        private const string TOPIC_DISPLAY = "/splitFlap/cmd/display/";

        public event EventHandler<SplitFlapDisplayEventArgs> SplitFlapDisplayChanged;

        public DevSplitFlap(IPublisherSubscriber com) : base(com, new List<string>() { TOPIC_DISPLAY }) { }

        public void InitializeAllSplitflaps()
        {
            base.SendMessage(TOPIC_INITALL, "");
        }

        public void ConfigureSplitflap(int setupId, int hardwareId)
        {
            string payload = JsonSerializer.Serialize(new Dictionary<string, int>() { { "setupId", setupId }, { "hardwareId", hardwareId } });
            base.SendMessage(TOPIC_CONFIGURE_SF, payload);
        }

        public void Display(string message)
        {
            string payload = JsonSerializer.Serialize(new Dictionary<string, string>() { { "message", message } });
            base.SendMessage(TOPIC_DISPLAY, payload);
        }

        protected override void ParseMessage(string fromTopic, string message)
        {
            if(fromTopic == TOPIC_DISPLAY)
            {
                var parsedMessage = GetValueFromMesage<string>("message", message);
                if (parsedMessage == null) parsedMessage = "?";
                SplitFlapDisplayEventArgs eventArgs = new(parsedMessage);
                SplitFlapDisplayChanged?.Invoke(this, eventArgs);
            }
        }

        private T GetValueFromMesage<T>(string parameter,string message)
        {
            var data = JsonSerializer.Deserialize<Dictionary<string, T>>(message);
            data.TryGetValue(parameter, out T value);
            return value;
        }
    }
}
