using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

namespace DaireApplication.DataBase;

public class ConfigrationTable
{
    public int Id { get; set; }
    public int Max { get; set; } = 0;
    public int Min { get; set; } = 0;
    public List<int> H_out { get; set; } = new();
    public List<int> FC_out { get; set; } = new();
    public List<int> SC_out { get; set; } = new();
    public int kp { get; set; } = 0;
    public int ki { get; set; } = 0;
    public int kd { get; set; } = 0;
    public int kl { get; set; } = 0;
    public string name { get; set; } = "";
    public float i_neut { get; set; } = 0;
    public float i_mot1 { get; set; } = 0;
    public float i_mot2 { get; set; } = 0;
    public float FC_Threshold { get; set; } = 3;
    public float HeatConRange { get; set; } = 50;

    public List<ConfigrationTable> ReadConfigrations()
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        List<ConfigrationTable> configrations = new List<ConfigrationTable>();

        if (File.Exists(filePath))
        {
            using StreamReader reader = new(filePath);
            string header = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                string[] columns = reader.ReadLine().Split(',');
                configrations.Add(new ConfigrationTable
                {
                    Id = int.Parse(columns[0]),
                    Max = int.Parse(columns[1]),
                    Min = int.Parse(columns[2]),
                    H_out = columns[3].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                    FC_out = columns[4].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                    SC_out = columns[5].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                    kp = int.Parse(columns[6]),
                    ki = int.Parse(columns[7]),
                    kd = int.Parse(columns[8]),
                    kl = int.Parse(columns[9]),
                    name=columns[10],
                    i_neut= float.Parse(columns[11]),
                    i_mot1= float.Parse(columns[12]),
                    i_mot2= float.Parse(columns[13]),
                    FC_Threshold = float.Parse(columns[14]),
                    HeatConRange = float.Parse(columns[15]),
                });
            }
            return configrations;
        }
        return null;
    }

    public int GetMaxId()
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        if (File.Exists(filePath))
        {
            return File.ReadAllLines(filePath)
                .Select(line => line.Split(','))
                .Where(columns => columns.Length > 0)
                .Select(columns => int.TryParse(columns[0], out int id) ? id : 0)
                .Max();
        }
        return -1;
    }

    public ConfigrationTable ReadConfigrationById(string id)
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        if (File.Exists(filePath))
        {
            foreach (var line in File.ReadLines(filePath))
            {
                string[] columns = line.Split(',');
                if (columns[0] == id)
                {
                    return new ConfigrationTable
                    {
                        Id = int.Parse(columns[0]),
                        Max = int.Parse(columns[1]),
                        Min = int.Parse(columns[2]),
                        H_out = columns[3].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                        FC_out = columns[4].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                        SC_out = columns[5].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(),
                        kp = int.Parse(columns[6]),
                        ki = int.Parse(columns[7]),
                        kd = int.Parse(columns[8]),
                        kl = int.Parse(columns[9]),
                        name=columns[10],
                        i_neut = float.Parse(columns[11]),
                        i_mot1 = float.Parse(columns[12]),
                        i_mot2 = float.Parse(columns[13]),
                        FC_Threshold = float.Parse(columns[14]),
                        HeatConRange = float.Parse(columns[15]),
                    };
                }
            }
        }
        return null;
    }

    public bool AddConfigration(ConfigrationTable data)
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        if (File.Exists(filePath))
        {
            string newEntry = string.Join(",", [
                GetMaxId() + 1,
                data.Max,
                data.Min,
                string.Join("|", data.H_out),
                string.Join("|", data.FC_out),
                string.Join("|", data.SC_out),
                data.kp,
                data.ki,
                data.kd,
                data.kl,
                data.name,
                data.i_neut,
                data.i_mot1,
                data.i_mot2,
                data.FC_Threshold,
                data.HeatConRange
            ]);
            File.AppendAllText(filePath, newEntry + Environment.NewLine);
            return true;
        }
        return false;
    }

    public bool DeleteConfigration(string id)
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        if (File.Exists(filePath))
        {
            var filteredLines = File.ReadLines(filePath).Where(line => !line.StartsWith(id + ",")).ToArray();
            File.WriteAllLines(filePath, filteredLines);
            return true;
        }
        return false;
    }

    public bool UpdateConfigration(ConfigrationTable updatedConfig)
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");
        if (File.Exists(filePath))
        {
            string[] lines = File.ReadAllLines(filePath);
            bool configFound = false;

            for (int i = 1; i < lines.Length; i++)
            {
                string[] columns = lines[i].Split(',');

                if (columns.Length < 10)
                    continue;

                if (int.Parse(columns[0]) == updatedConfig.Id)
                {
                    columns[1] = updatedConfig.Max.ToString();
                    columns[2] = updatedConfig.Min.ToString();
                    columns[3] = string.Join("|", updatedConfig.H_out);
                    columns[4] = string.Join("|", updatedConfig.FC_out);
                    columns[5] = string.Join("|", updatedConfig.SC_out);
                    columns[6] = updatedConfig.kp.ToString();
                    columns[7] = updatedConfig.ki.ToString();
                    columns[8] = updatedConfig.kd.ToString();
                    columns[9] = updatedConfig.kl.ToString();
                    columns[10] = updatedConfig.name;
                    columns[11] = updatedConfig.i_neut.ToString(CultureInfo.InvariantCulture);
                    columns[12] = updatedConfig.i_mot1.ToString(CultureInfo.InvariantCulture);
                    columns[13] = updatedConfig.i_mot2.ToString(CultureInfo.InvariantCulture);
                    columns[14] = updatedConfig.FC_Threshold.ToString(CultureInfo.InvariantCulture);
                    columns[15] = updatedConfig.HeatConRange.ToString(CultureInfo.InvariantCulture);

                    lines[i] = string.Join(",", columns);
                    configFound = true;
                    break;
                }
            }

            if (configFound)
            {
                File.WriteAllLines(filePath, lines);
                return true;
            }
        }
        return false;
    }
}
