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

namespace InABox.Core
{
    public class DFLayoutMultiImageProperties : DFLayoutFieldProperties<List<byte[]>>
    {
        [CheckBoxEditor]
        public bool DisableLibrary { get; set; } = false;

        public override string FormatValue(object? value)
        {
            return value != null ? "Yes" : "";
        }

        public override object? ParseValue(object? value)
        {
            List<string>? values = null;
            if (value is List<byte[]> list)
                return list;
            else if(value is JArray jArray)
                values = jArray.Select(x => x.ToString()).ToList();
            else if(value is string str)
            {
                if (Guid.TryParse(str, out var id))
                {
                    return new List<byte[]>();
                }
                values = Serialization.Deserialize<List<string>>(str);
            }

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

            return null;
        }

        protected override void LoadProperties()
        {
            base.LoadProperties();
            DisableLibrary = GetProperty("DisableLibrary", false);
        }

        protected override void SaveProperties()
        {
            base.SaveProperties();
            SetProperty("DisableLibrary", DisableLibrary);
        }
    }
}