using Inspectron.Settings;
using System.Text.Json;
using System.Text.Json.Serialization;
using VisionBuilder.UI.Common;

namespace CandyboxPlugin.Modules.Barcode;

public class CandyboxBarcodeReaderSettings(string CameraName) : ISettings
{
    public string ComPort { get; set; } = "COM3";

    public List<BarcodeRecipeMapping> BarcodeRecipeMappings { get; set; } = new List<BarcodeRecipeMapping>();

    public void RegisterSettings(InspectronSettings settings)
    {
        settings.RegisterSimple(this, () => ComPort, CameraName + "/Barcode reader", nameof(ComPort));
        settings.RegisterSimple(this, () => BarcodeRecipeMappings, CameraName + "/Barcode reader", nameof(BarcodeRecipeMappings));
    }
}

public class BarcodeRecipeMapping
{
    public string Barcode { get; set; }
    public string RecipeName { get; set; }
}

public class ListBarcodeRecipeMappingConverter : ITypeConverter
{
    public object ConvertFrom(object value)
    {
        if (value is string json)
        {
            try
            {
                return JsonSerializer.Deserialize<List<BarcodeRecipeMapping>>(json, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    Converters = { new JsonStringEnumConverter() }
                });
            }
            catch (JsonException)
            {
                throw new InvalidOperationException("Failed to deserialize BarcodeRecipeMapping list from JSON.");
            }
        }
        throw new InvalidOperationException("Value must be a JSON string.");
    }

    public object ConvertTo(object value, Type destinationType)
    {
        if (value is List<BarcodeRecipeMapping> list && destinationType == typeof(string))
        {
            return JsonSerializer.Serialize(list, new JsonSerializerOptions
            {
                WriteIndented = false,
                Converters = { new JsonStringEnumConverter() }
            });
        }
        throw new InvalidOperationException("Value must be a List<BarcodeRecipeMapping> and destinationType must be string.");

    }
}