using System;
using System.Collections.Generic;
using System.Linq;
using InABox.Core;

namespace InABox.Core
{
    public class DFLayoutLookupValue : IDFLayoutValue<Guid>
    {
        public Guid ID { get; set; }
        public string Text { get; set; }
        public Dictionary<string, object?> Values { get; set; }

        public DFLayoutLookupValue()
        {
            ID = Guid.Empty;
            Text = "";
            Values = new Dictionary<string, object?>();
        }
        
        /*public void Load(string serialized)
        {
            if (!serialized.IsNullOrWhiteSpace())
            {
                try
                {
                    var value = Serialization.Deserialize<DFLayoutLookupValue>(serialized, true);
                    ID = value?.ID ?? Guid.Empty;
                    Text = value?.Text ?? string.Empty;
                    Values = value?.Values ?? new Dictionary<string, object?>();
                }
                catch
                {
                    if (Guid.TryParse(serialized, out var id))
                    {
                        ID = id;
                        Text = id.ToString();
                        Values = new Dictionary<string, object?>();
                    }
                    else
                    {
                        ID = Guid.Empty;
                        Text = serialized;
                        Values = new Dictionary<string, object?>();
                    }
                    
                }
            }
        }*/

        public void Serialize(DFSaveStorageEntry storage)
        {
            storage.SetValue(Text);
            storage.AddValue("ID", ID);
            var valuesExcludingID = Values.Where(x => !String.Equals(x.Key, "ID")).ToArray();
            foreach(var (key, value) in valuesExcludingID)
            {
                if(value is byte[] bArr)
                    storage.AddBlobValue(key, bArr);
                else
                    storage.AddValue(key, value);
            }
        }

        public void Deserialize(DFLoadStorageEntry storage)
        {
            Text = storage.GetValue<string>() ?? string.Empty;
            ID = storage.GetValue<Guid>("ID");
            foreach(var (key, value) in storage.SubItems())
            {
                if (!key.Equals("ID"))
                {
                    Values.Add(key, value);
                }
            }
        }
    }
}