using System;
using System.Collections.Generic;

namespace InABox.Core
{
    public abstract class DFLayoutObject : BaseObject
    {
        private Dictionary<string, object> _properties = new Dictionary<string, object>();

        protected void SetProperty(string name, object? value)
        {
            if (value == null)
                return;
            if (value.GetType().IsEnum)
                _properties[name] = value.ToString();
            else
                _properties[name] = value;
        }

        protected T GetProperty<T>(string key, T defaultvalue)
        {
            var result = defaultvalue;
            if (_properties.ContainsKey(key))
                try
                {
                    if (typeof(T).IsEnum)
                        result = (T)Enum.Parse(typeof(T), _properties[key].ToString());
                    else
                        result = (T)CoreUtils.ChangeType(_properties[key], typeof(T));
                }
                catch (Exception e)
                {
                    Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
                }

            return result;
        }

        protected abstract void LoadProperties();

        protected abstract void SaveProperties();

        public void LoadFromString(string properties)
        {
            SetObserving(false);
            if (!string.IsNullOrEmpty(properties))
                _properties = Serialization.Deserialize<Dictionary<string, object>>(properties);
            else
                _properties = new Dictionary<string, object>();
            LoadProperties();
            SetObserving(true);
        }

        public string SaveToString()
        {
            _properties.Clear();
            SaveProperties();
            return Serialization.Serialize(_properties);
        }
    }
}