using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PlantBox.Shared.Communication;
using PlantBox.Shared.Communication.Commands;

namespace PlantBox.Broker
{
    class ClientManager : TcpManager
    {
        public ClientManager(Broker broker) : base(broker)
        {

        }

        protected override string LogPrefix => "Client";
        protected override int ListeningPort => Connection.TCP_CLIENT_PORT;

        protected override void CaptorsCommand(CommandStream commandStream, CommandPacket packet)
        {
            CaptorsRequest captorsRequest = new CaptorsRequest().Deserialize(packet.Arguments);
            ulong id = packet.ID;
            PlantBox plantBox = Broker.PlantBoxesManager[id];

            CaptorsResponse response;

            if (plantBox == null)
            {
                response = new CaptorsResponse(0, 0, 0, 0);
            }
            else
            {
                response = new CaptorsResponse(plantBox.Humidity.Value, plantBox.Luminosity.Value, plantBox.Temperature.Value, plantBox.TankLevel);
            }

            commandStream.Send(response.ToCommandPacket(id));
        }

        protected override void HistoricCommand(CommandStream commandStream, CommandPacket packet)
        {
            double[] FillArray(double[] values, int length)
            {
                // Check if need
                if (values.Length >= length)
                {
                    return values.Reverse().Take(length).Reverse().ToArray();
                }

                var array = new double[length];

                if (values.Length > 0)
                {
                    int startIndex = length - values.Length;

                    values.CopyTo(array, startIndex);
                }

                return array;
            }

            HistoricRequest historicRequest = new HistoricRequest().Deserialize(packet.Arguments);
            ulong id = packet.ID;
            PlantBox plantBox = Broker.PlantBoxesManager[id];
            int count = historicRequest.Number;

            HistoricResponse response;

            if (plantBox == null)
            {
                response = new HistoricResponse(TimeSpan.MinValue, Array.Empty<double>(), Array.Empty<double>(), Array.Empty<double>());
            }
            else
            {
                HistoricManager historic = plantBox.HistoricManager;

                IReadOnlyList<CaptorsValue> captorsValues;
                switch (historicRequest.Interval)
                {
                    case HistoricInterval.Minutely:
                        captorsValues = historic.MinutesHistoric;
                        break;
                    case HistoricInterval.Hourly:
                        captorsValues = historic.HoursHistoric;
                        break;
                    case HistoricInterval.Daily:
                        captorsValues = historic.DaysHistoric;
                        break;
                    case HistoricInterval.Weekly:
                        captorsValues = historic.WeeksHistoric;
                        break;
                    case HistoricInterval.Monthly:
                        captorsValues = historic.MonthsHistoric;
                        break;
                    default:
                        throw new InvalidOperationException("How did you just got here? Even 『 』can't");
                }

                response = new HistoricResponse
                (
                    DateTime.Now - plantBox.LastMeasureDate,
                    FillArray(captorsValues.Select(x => x.Humidity).ToArray(), count),
                    FillArray(captorsValues.Select(x => x.Luminosity).ToArray(), count),
                    FillArray(captorsValues.Select(x => x.Temperature).ToArray(), count)
                );
            }

            commandStream.Send(response.ToCommandPacket(id));
        }

        protected override void InfoCommand(CommandStream commandStream, CommandPacket packet)
        {
            InfoRequest infoRequest = new InfoRequest().Deserialize(packet.Arguments);
            ulong id = packet.ID;
            PlantBox plantBox = Broker.PlantBoxesManager[id];

            InfoResponse response;

            if (plantBox == null)
            {
                response = new InfoResponse("", default, default, 0, 0, 0, 0, 0, 0);
            }
            else
            {
                plantBox.UpdateState();

                response = new InfoResponse
                (
                    plantBox.Name, plantBox.Type, plantBox.State,
                    plantBox.Humidity.Min, plantBox.Humidity.Max,
                    plantBox.Luminosity.Min, plantBox.Luminosity.Max,
                    plantBox.Temperature.Min, plantBox.Temperature.Max
                );
            }
            commandStream.Send(response.ToCommandPacket(id));
        }

        protected override void PingCommand(CommandStream commandStream, CommandPacket packet)
        {
            var ping = new PingCommand().Deserialize(packet.Arguments);

            commandStream.Send(ping.ToCommandPacket(packet.ID));
        }
    }
}
