using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace InABox.Core
{
    public class DFLayoutMultiSignaturePadProperties : DFLayoutFieldProperties<Dictionary<string, byte[]>>
    {
        public override string FormatValue(object value)
        {
            return value != null ? "Yes" : "";
        }

        public override object? ParseValue(object value)
        {
            if (value is Dictionary<string, byte[]> dict)
                return dict;

            Dictionary<string, string>? values = null;
            if (value is JObject jObject)
                values = jObject.ToObject<Dictionary<string, string>>();
            else if(value is string str)
            {
                if (Guid.TryParse(str, out var id))
                {
                    return new List<byte[]>();
                }
                values = Serialization.Deserialize<Dictionary<string, string>>(str);
            }

            if (values != null)
                try
                {
                    var convertedValues = new Dictionary<string, byte[]>();
                    foreach (var v in values.Keys)
                    {
                        convertedValues.Add(v, Convert.FromBase64String(values[v]));
                    }
                    return convertedValues;
                }
                catch (Exception)
                {
                    return null;
                }

            return null;
        }
    }
}
