using Newtonsoft.Json;
using SFI.COMM.ENTITY;
using SFI.COMM.LIB.Redis;
using SFI.COMM.SESSION;
using System;
using System.Collections.Generic;
using System.Text;

namespace SFI.COMM.BASESYSTEM
{
    public static class CommunicationController
    {
        public const string ServerKey = "SFICOMM-WEBSERVER";
        public static RedisChannel Redis { get; set; }
        public static string ClientKey { get; set; }
        public static SystemTypes SystemType { get; set; }
        public static int MaxThreadCount { get; set; }

        public static void Start(SystemTypes SystemType_, string ClientKeyForServices_, string Server_, int Port_, string Password_, int MaxThreadCountForServices_ = 1, string LicenceFilePath_ = "")
        {
            if (SystemType_ == SystemTypes.WebServer)
            {
                LicenseController.Start(LicenceFilePath_);
                ClientKeyForServices_ = CommunicationController.ServerKey;
            }


            CommandController.Start();

            CommunicationController.MaxThreadCount = MaxThreadCountForServices_;
            CommunicationController.SystemType = SystemType_;
            CommunicationController.ClientKey = ClientKeyForServices_;
            CommunicationController.Redis = new RedisChannel(Server_, Port_, Password_, ClientKeyForServices_, "SFICOMMPUBLICCHANNEL", (channelData) => CommunicationController.Interpreter(channelData));
            CommunicationController.Redis.Start();
        }

        public static void Stop()
        {
            CommunicationController.Redis.Stop();
            CommandController.Stop();
        }


        public static void Interpreter(string channelData)
        {
            try
            {
                ChannelCommand command_ = JsonConvert.DeserializeObject<ChannelCommand>(channelData);
                if (command_.TargetName.Equals(CommunicationController.ClientKey))
                    CommandController.RunCommand(command_);
            }
            catch (Exception exc)
            {

            }
        }


        public static void Publish(ChannelCommand Command_) => CommunicationController.Redis.SendData(Command_);
        public static void Publish(string ChannelName_, ChannelCommand Command_) => CommunicationController.Redis.SendData(ChannelName_, Command_);



       
    }
}
