using System;
using System.Text;

namespace InABox.Core
{
    public class DFLayoutEmbeddedMediaValue : IDFLayoutValue<byte[]>
    {
        public Guid ID { get; set; }
        public byte[]? Data { get; set; }
        public byte[]? Thumbnail { get; set; }

        public void Deserialize(DFLoadStorageEntry storage)
        {
            var value = storage.GetValue();

            if (value is Guid id)
            {
                ID = id;
            }
            else if (value is string str)
            {
                if(Guid.TryParse(str, out id))
                    ID = id;
                else
                {
                    try
                    {
                        var tuple = Serialization.Deserialize<(Guid, byte[])>(str,true);
                        ID = tuple.Item1;
                        Thumbnail = tuple.Item2;
                        return;
                    }
                    catch (Exception e)
                    {
                        try
                        {
                            var data = Convert.FromBase64String(str);
                            ID = Guid.Empty;
                            Thumbnail = data;
                            Data = data;
                            return;
                        }
                        catch (Exception e2)
                        {
                            ID = Guid.Empty;
                        }

                    }
                }
                
            }

            Thumbnail = storage.GetValue<byte[]>("Thumbnail");
        }

        public void Serialize(DFSaveStorageEntry storage)
        {
            storage.SetValue(ID);
            storage.AddBlobValue("Thumbnail", Thumbnail);
        }
    }
}