using System.Collections.Concurrent;

namespace ConfigOperator;

public class HardwareFileLoader(Hardwares hardwares)
{
    public bool Load()
    {
        if (!DierctoryHelper.GetAllFiles(Paths.HardwareFolder, out List<string>? hardwareFiles) || hardwareFiles is null)
            return false;

        foreach (var item in hardwareFiles)
        {
            if (!XmlHelper.DeserializeXml(item, out HardwareSaveXML? output) || output is null)
                continue;
            if (output.Mini8 is null)
                continue;
            if (output.Channels is null)
                continue;

            hardwares.Mini8s[output.Mini8.Index] = output.Mini8;
            ConcurrentDictionary<byte, ChannelData> channels = [];

            foreach (var channel in output.Channels)
                channels[channel.ChannelIndex] = channel;

            hardwares.Mini8Channels[output.Mini8.Index] = channels;
        }

        //LoadHardwareSetValue();
        return true;
    }

    public bool SaveSingleMini8(byte mini8Index)
    {
        if (!hardwares.Mini8s.TryGetValue(mini8Index, out Mini8Data? mini8) || mini8 is null)
            return false;

        HardwareSaveXML saveItems = new()
        {
            Mini8 = mini8,
            Channels = [.. hardwares.Mini8Channels[mini8Index].Values],
        };
        string path = Path.Combine(Paths.HardwareFolder, $"{mini8.Name}.xml");
        return XmlFileHelper.WriteFile(path, saveItems);
    }

    public void Save()
    {
        foreach (var mini8 in hardwares.Mini8s)
        {
            HardwareSaveXML saveItems = new()
            {
                Mini8 = mini8.Value,
                Channels = [.. hardwares.Mini8Channels[mini8.Key].Values],
            };
            string path = Path.Combine(Paths.HardwareFolder, $"{mini8.Value.Name}.xml");
            XmlFileHelper.WriteFile(path, saveItems);
        }
    }
}

public class HardwareSaveXML
{
    public Mini8Data? Mini8 { get; set; }
    public List<ChannelData>? Channels { get; set; }
}
