using System;
using System.IO;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace B24SiemensEmulator
{
    public class PacketConfiguration
    {
        public bool Lifebit { get; set; }
        public bool KameraStart { get; set; }
        public int Materialnummer { get; set; }
        public int ArtikelnummerBall { get; set; }
        public int MaterialnummerFoil { get; set; }
        public string Chargennummer { get; set; } = string.Empty;

        public static PacketConfiguration FromPLCPacket(PLCPacket packet)
        {
            return new PacketConfiguration
            {
                Lifebit = packet.Lifebit,
                KameraStart = packet.KameraStart,
                Materialnummer = packet.Materialnummer,
                ArtikelnummerBall = packet.ArtikelnummerBall,
                MaterialnummerFoil = packet.MaterialnummerFoil,
                Chargennummer = packet.Chargennummer
            };
        }

        public PLCPacket ToPLCPacket()
        {
            return new PLCPacket
            {
                Lifebit = Lifebit,
                KameraStart = KameraStart,
                Materialnummer = Materialnummer,
                ArtikelnummerBall = ArtikelnummerBall,
                MaterialnummerFoil = MaterialnummerFoil,
                Chargennummer = PLCPacket.ValidateAndTrimChargennummer(Chargennummer)
            };
        }
    }

    public class ConfigurationManager
    {
        private const string DefaultFileName = "PLCPacketConfig.json";
        private const string FileFilter = "JSON files (*.json)|*.json|All files (*.*)|*.*";

        public static bool SaveConfiguration(PacketConfiguration config, string? filePath = null)
        {
            try
            {
                string path = filePath ?? GetSaveFilePath();
                if (string.IsNullOrEmpty(path))
                    return false;

                string json = JsonConvert.SerializeObject(config, Formatting.Indented);
                File.WriteAllText(path, json);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to save configuration: {ex.Message}", "Save Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        public static PacketConfiguration? LoadConfiguration(string? filePath = null)
        {
            try
            {
                string path = filePath ?? GetLoadFilePath();
                if (string.IsNullOrEmpty(path) || !File.Exists(path))
                    return null;

                string json = File.ReadAllText(path);
                var config = JsonConvert.DeserializeObject<PacketConfiguration>(json);
                
                if (config == null)
                {
                    MessageBox.Show("Invalid configuration file format.", "Load Error", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }

                // Validate loaded configuration
                if (!PLCPacket.IsValidChargennummer(config.Chargennummer))
                {
                    MessageBox.Show("Invalid Chargennummer in configuration file. It will be corrected.", 
                        "Load Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    config.Chargennummer = PLCPacket.ValidateAndTrimChargennummer(config.Chargennummer);
                }

                return config;
            }
            catch (JsonException ex)
            {
                MessageBox.Show($"Failed to parse configuration file: {ex.Message}", "Load Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to load configuration: {ex.Message}", "Load Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private static string GetSaveFilePath()
        {
            using var saveDialog = new SaveFileDialog
            {
                Filter = FileFilter,
                FileName = DefaultFileName,
                Title = "Save PLC Packet Configuration"
            };

            return saveDialog.ShowDialog() == DialogResult.OK ? saveDialog.FileName : string.Empty;
        }

        private static string GetLoadFilePath()
        {
            using var openDialog = new OpenFileDialog
            {
                Filter = FileFilter,
                Title = "Load PLC Packet Configuration"
            };

            return openDialog.ShowDialog() == DialogResult.OK ? openDialog.FileName : string.Empty;
        }

        public static bool ValidateConfiguration(PacketConfiguration config)
        {
            if (config == null)
                return false;

            return PLCPacket.IsValidChargennummer(config.Chargennummer);
        }
    }
}