using UnityEngine;

namespace NBF.Setting
{
    public interface IOptionBase
    {
        string Name { get; }
        void Initialize(ISettings root);
        void Apply();
        int GetValue();
        void SetValue(int index);
        bool HaveNotApple();
        ISettings Root { get; }
        string GetDisplayString();
    }

    public abstract class OptionBase : IOptionBase
    {
        protected string SaveKey => $"Setting_{Group}_{Name}";

        public abstract string Name { get; }

        /// <summary>
        /// 所在组
        /// </summary>
        public abstract string Group { get; }

        /// <summary>
        /// 所在分切页
        /// </summary>
        public abstract string Tab { get; }

        /// <summary>
        /// 默认值
        /// </summary>
        protected abstract int DefaultValue { get; }

        /// <summary>
        /// 当前的值
        /// </summary>
        protected int Value;

        /// <summary>
        /// 保存的值
        /// </summary>
        protected int SaveValue;

        public virtual bool HaveNotApple()
        {
            return !Value.Equals(SaveValue);
        }

        public ISettings Root { get; private set; }


        public void Initialize(ISettings root)
        {
            Root = root;
            Load();
            OnInitialize();
            if (!PlayerPrefs.HasKey(SaveKey))
            {
                OnSetDefaultValue();
            }

            Apply();
        }

        /// <summary>
        /// 加载用户的设置
        /// </summary>
        public virtual void Load()
        {
            var value = PlayerPrefs.GetInt(SaveKey, DefaultValue);
            Value = value;
            SaveValue = value;
        }

        public virtual void Apply()
        {
            PlayerPrefs.SetInt(SaveKey, Value);
            SaveValue = Value;
            OnApply();
        }

        public virtual void Reset()
        {
            Value = DefaultValue;
        }

        public virtual void Cancel()
        {
        }


        public virtual string GetDisplayString()
        {
            return GetValue().ToString();
        }

        public virtual int GetValue()
        {
            return Value;
        }

        public virtual void SetValue(int value)
        {
            Value = value;
        }


        protected virtual void OnInitialize()
        {
        }

        protected virtual void OnSetDefaultValue()
        {
            Value = DefaultValue;
            SaveValue = DefaultValue;
        }

        protected abstract void OnApply();
    }
}