using PlantBox.Shared.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace PlantBox.Shared.Communication.Commands
{
    public class HistoricResponse : CommandSerializable<HistoricResponse>
    {
        public const char ValueSeparator = '/';

        public override Command Command => Command.Historic;

        public TimeSpan Time { get; set; }
        public double[] Humidities { get; set; }
        public double[] Luminosities { get; set; }
        public double[] Temperatures { get; set; }

        public HistoricResponse()
        {

        }
        public HistoricResponse(TimeSpan time, double[] humidities, double[] luminosities, double[] temperatures)
        {
            Time = time;
            Humidities = humidities;
            Luminosities = luminosities;
            Temperatures = temperatures;
        }

        public override HistoricResponse Deserialize(string[] arguments)
        {
            double[] GetArray(string argument)
            {
                return argument.Split(ValueSeparator).Select(x => x.ToDouble()).ToArray();
            }

            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }
            if (arguments.Length < 4)
            {
                throw new ArgumentException($"Excepted 4 arguments, got {arguments.Length}");
            }

            Time = TimeSpan.FromSeconds(arguments[0].ToDouble());
            Humidities   = GetArray(arguments[1]);
            Luminosities = GetArray(arguments[2]);
            Temperatures = GetArray(arguments[3]);

            return this;
        }

        public override string[] Serialize()
        {
            string Join(double[] values)
            {
                return string.Join(ValueSeparator.ToString(), values.Select(x => x.ToArgument()));
            }

            return new[]
            {
                Time.TotalSeconds.ToArgument(),
                Join(Humidities),
                Join(Luminosities),
                Join(Temperatures)
            };
        }
    }
}
