using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;
using Inspectron.Settings;
using VisionBuilder.UI.Common;
using VisionBuilder.UI.Common.Utils;

namespace B24SiemensPlugin;

public class B24SiemensSettings:ISettings
{
    public string CameraName { get; }

    public B24SiemensSettings(string cameraName)
    {
        CameraName = cameraName;
    }

    public List<SiemensRecipeMapping> RecipeMappings { get; set; } = new List<SiemensRecipeMapping>();

    public void RegisterSettings(InspectronSettings settings)
    {
        settings.RegisterSimple(this, ()=>this.RecipeMappings,$"{CameraName}/Siemens(B24)", nameof(RecipeMappings));
    }
}



public class SiemensRecipeMapping
{
    public int MaterialNumber { get; set; }
    public string RecipeName { get; set; }

    public override string ToString()
    {
        return $"{MaterialNumber} -> {RecipeName}";
    }
}

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

    }

    public object ConvertTo(object value, Type destinationType)
    {
        if (value is List<SiemensRecipeMapping> mappings)
        {
            try
            {
                return JsonSerializer.Serialize(mappings, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    Converters = { new JsonStringEnumConverter() }
                });
            }
            catch (JsonException)
            {
                throw new InvalidOperationException("Failed to serialize SiemensRecipeMapping list to JSON.");
            }
        }
        throw new InvalidOperationException("Value must be a List<SiemensRecipeMapping>.");

    }
}