using System;
using SGModule.Common.Helper;

namespace SGModule.DataStorage {
    public class DataStorage<T> {
        private readonly T _defaultValue;
        private readonly string _key;
        private readonly Action<T, T> _onChange;

        public DataStorage(string key, T defaultValue = default, Action<T, T> onChange = null, bool cloudSave = true) {
            if (!DataKeyDic.Register<T>(key, cloudSave)) {
                throw new Exception($"Key {key} already exists.");
            }

            _key = key;
            _defaultValue = defaultValue;
            _onChange = onChange;
        }

        public T Value {
            get => DataManager.Instance.LoadData(_key, _defaultValue);
            set => SaveAndDispatch(value);
        }

        /// <summary>
        ///     手动触发保存（即使数据本身未变更）
        /// </summary>
        public void Save() {
            SaveAndDispatch(Value, true);
        }

        /// <summary>
        ///     更新值并创建变更追踪，分发并保存
        /// </summary>
        private void SaveAndDispatch(T newValue, bool forceSave = false) {
            var oldValue = Value;

            // 如果不强制保存且值没有变动，直接返回
            if (!forceSave && CommonUtils.DeepEquals(oldValue, newValue)) {
                return;
            }

            // 分发变更通知（old -> new）
            _onChange?.Invoke(oldValue, newValue);

            // 保存新值
            DataManager.Instance.SaveData(_key, newValue);
        }
    }
}
