using NIDAQmxConst;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataCollection.Tools
{
    internal static class ServiceConfigTools
    {
        private readonly static string ConfigPath =System.AppDomain.CurrentDomain.BaseDirectory +"Config.json";
        public static ServiceConfig ReadConfig()
        {
            ServiceConfig? config = new ServiceConfig();
            if(System.IO.File.Exists(ConfigPath))
            {
                try
                {
                    config = Newtonsoft.Json.JsonConvert.DeserializeObject<ServiceConfig>(System.IO.File.ReadAllText(ConfigPath));
                }
                catch
                {

                }
            }
            config ??= ServiceConfig.Default;
            int count = config.Coefficients.Count;
            if(count<ServiceConstant.ChannelCount)
            {
                config.Coefficients.AddRange(Enumerable.Range(0, ServiceConstant.ChannelCount - count).Select(x => new SensorCoefficient()));
            }
            else if(count>ServiceConstant.ChannelCount)
            {
                config.Coefficients.RemoveRange(ServiceConstant.ChannelCount, ServiceConstant.ChannelCount - count);
            }
            SaveConfig(config);
            return config;

        }
        public static void SaveConfig(ServiceConfig config)

        {
            config ??= ServiceConfig.Default;
            if(System.IO.File.Exists(ConfigPath))
            {
                System.IO.File.Delete(ConfigPath);
            }
            int count = config.Coefficients.Count;
            if (count < ServiceConstant.ChannelCount)
            {
                config.Coefficients.AddRange(Enumerable.Range(0, ServiceConstant.ChannelCount - count).Select(x => new SensorCoefficient()));
            }
            else if (count > ServiceConstant.ChannelCount)
            {
                config.Coefficients.RemoveRange(ServiceConstant.ChannelCount, ServiceConstant.ChannelCount - count);
            }
            try
            {
                System.IO.File.WriteAllText(ConfigPath, Newtonsoft.Json.JsonConvert.SerializeObject(config, Newtonsoft.Json.Formatting.Indented));
            }
            catch
            {

            }
        }
    }

}
