import { EventManager } from './EventManager'

// 装饰器工厂函数
export function Ob(eventName?: string) {
  return function (target: any, propertyKey: string) {
    // 存储原始值的弱映射
    const privateMap = new WeakMap()

    // 定义getter/setter
    Object.defineProperty(target, propertyKey, {
      get: function () {
        return privateMap.get(this)?.value
      },
      set: function (newValue) {
        const oldValue = privateMap.get(this)?.value
        if (oldValue == newValue) return
        privateMap.set(this, { value: newValue })
        // 触发事件
        const eventMgr = EventManager.Instance()
        const finalEventName = eventName || `${target.constructor.name.toLowerCase()}:${propertyKey}`
        const data = { property: propertyKey, oldValue, newValue }
        eventMgr.Emit(finalEventName, data)
        // 触发通用事件
        const commEventName = `${target.constructor.name.toLowerCase()}:property`
        const commData = { property: propertyKey, oldValue, newValue }
        eventMgr.Emit(commEventName, commData)
      },
      enumerable: true,
      configurable: true,
    })
  }
}
