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

namespace DaireApplication.DataBase;

public class Mapping
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Address { get; set; } = "";
    public bool IsRead { get; set; } = false;
    public List<int> BitNumbers { get; set; } = new();
 

    public ushort getSetTempAddress(int tempAddress) 
    {
        string tAddress = "4000";
        tempAddress -= 30004;
        tAddress += tempAddress;
        return ushort.Parse(tAddress);
    }
    public List<Mapping> ReadMappings()
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");
        List<Mapping> mappings = new();

        if (File.Exists(filePath))
        {
            using StreamReader reader = new(filePath);
            string header = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                string[] columns = reader.ReadLine().Split(',');
                mappings.Add(new Mapping
                {
                    Id = int.Parse(columns[0]),
                    Name = columns[1],
                    Address = columns[2],
                    IsRead = columns[3] == "1"|| columns[3] == "True",
                    BitNumbers =columns[4]!=""? columns[4].Split('|').Select(int.Parse).ToList():new List<int>()
                });
            }
            return mappings;
        }
        return null;
    }

    public int GetMaxId()
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.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 Mapping ReadMappingById(string id)
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");
        if (File.Exists(filePath))
        {
            foreach (var line in File.ReadLines(filePath))
            {
                string[] columns = line.Split(',');
                if (columns[0] == id)
                {
                    return new Mapping
                    {
                        Id = int.Parse(columns[0]),
                        Name = columns[1],
                        Address = columns[2],
                        IsRead = columns[3] == "1",
                        BitNumbers = columns[4].Split('|').Select(int.Parse).ToList()
                    };
                }
            }
        }
        return null;
    }

    public bool AddMapping(Mapping data)
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");
        if (File.Exists(filePath))
        {
            string newEntry = string.Join(",", [
                GetMaxId() + 1,
                data.Name,
                data.Address,
                data.IsRead ? "1" : "0",
                string.Join("|", data.BitNumbers)
            ]);
            File.AppendAllText(filePath, newEntry + Environment.NewLine);
            return true;
        }
        return false;
    }

    public bool DeleteMapping(string id)
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.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 UpdateMapping(Mapping updatedMapping)
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");
        if (File.Exists(filePath))
        {
            string[] lines = File.ReadAllLines(filePath);
            bool mappingFound = false;

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

                if (columns.Length < 5)
                    continue;

                if (int.Parse(columns[0]) == updatedMapping.Id)
                {
                    columns[1] = updatedMapping.Name;
                    columns[2] = updatedMapping.Address;
                    columns[3] = updatedMapping.IsRead ? "1" : "0";
                    columns[4] = string.Join("|", updatedMapping.BitNumbers);
                    lines[i] = string.Join(",", columns);
                    mappingFound = true;
                    break;
                }
            }

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

    public bool DeleteBitNumber(int id, int bitNumber)
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");
        if (!File.Exists(filePath))
            return false;

        List<Mapping> records = ReadMappings();
        Mapping? record = records.Find(x => x.Id == id);

        if (record != null && record.BitNumbers.Remove(bitNumber)) // Remove bit number if found
        {
            string header;
            using (StreamReader sr = new StreamReader(filePath))
            {
                header = sr.ReadLine() ?? string.Empty;
            }

            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine(header);
                string bitNumbersStr = "";
                foreach (var rec in records)
                {
                    if (rec.Id==id)
                    {
                         bitNumbersStr = record.BitNumbers.Count > 0 ? string.Join("|", record.BitNumbers) : "";
                        writer.WriteLine($"{rec.Id},{rec.Name},{rec.Address},{rec.IsRead},{bitNumbersStr}");

                    }
                    else
                    {
                        bitNumbersStr = rec.BitNumbers.Count > 0 ? string.Join("|", rec.BitNumbers) : "";
                        writer.WriteLine($"{rec.Id},{rec.Name},{rec.Address},{rec.IsRead},{bitNumbersStr}");
                    }
                   
                }
            }
            return true;
        }
        return false;
    }

}
