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

namespace DaireApplication.DataBase
{
    public class ErrorSettingsTable
    {
        public int Id { get; set; }
        public int gridFreq { get; set; }
        public int phaseNumber { get; set; }
        public int phaseVoltage { get; set; }
        public bool extPower { get; set; }

        public List<ErrorSettingsTable>? ReadErrorSettings()
        {
            string filePath = DataPathManager.GetDataFilePath("ErrorSettings.csv");

            if (!File.Exists(filePath))
                return null;

            string[] lines = File.ReadAllLines(filePath);
            List<ErrorSettingsTable> errors = new();

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

                errors.Add(new ErrorSettingsTable
                {
                    Id = int.Parse(columns[0]),
                    gridFreq = int.Parse(columns[1]),
                    phaseNumber = int.Parse(columns[2]),
                    extPower = columns[3] == "1",
                    phaseVoltage = int.Parse(columns[4]),
                });
            }

            return errors;
        }

        public bool UpdateError(ErrorSettingsTable updatedError)
        {
            string filePath = DataPathManager.GetDataFilePath("ErrorSettings.csv");

            if (!File.Exists(filePath))
                return false;

            string[] lines = File.ReadAllLines(filePath);
            bool updated = false;

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

                if (int.Parse(columns[0]) == updatedError.Id)
                {
                    columns[1] = updatedError.gridFreq.ToString();
                    columns[2] = updatedError.phaseNumber.ToString();
                    columns[3] = updatedError.extPower ? "1" : "0";
                    columns[4] = updatedError.phaseVoltage .ToString();
                    lines[i] = string.Join(",", columns);
                    updated = true;
                    break;
                }
            }

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

            return false;
        }
    }
}
