/**
 * Redux Toolkit 适配器
 * 
 * 将 Redux Toolkit store 映射到 Secra 状态抽象
 * 
 * 使用说明：
 * 1. 需要安装 @reduxjs/toolkit 作为 peerDependency
 * 2. 每个状态实例对应一个 Redux slice
 * 3. 支持 Redux DevTools 集成（如果可用）
 * 4. 支持中间件和开发模式
 * 
 * @example
 * ```typescript
 * import { ReduxAdapter } from '@vlian/framework/state';
 * 
 * const adapter = new ReduxAdapter({ devMode: true });
 * const state = adapter.createInstance(0, { id: 'counter' });
 * 
 * state.set(1);
 * console.log(state.get()); // 1
 * ```
 */ "use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ReduxAdapter", {
    enumerable: true,
    get: function() {
        return ReduxAdapter;
    }
});
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
/**
 * Redux 状态实例实现
 * 
 * 将 Redux slice 映射到 IStateInstance 接口
 * 
 * @template T - 状态值类型
 */ let ReduxStateInstance = class ReduxStateInstance {
    /**
   * 获取当前状态值
   */ get() {
        if (this.destroyed) {
            throw new Error(`ReduxStateInstance ${String(this.id)} has been destroyed`);
        }
        const state = this.store.getState();
        return state[this.sliceName] ?? this.previousValue;
    }
    /**
   * 更新状态值
   */ set(valueOrUpdater) {
        if (this.destroyed) {
            throw new Error(`ReduxStateInstance ${String(this.id)} has been destroyed`);
        }
        const currentValue = this.get();
        let newValue;
        // 处理函数式更新
        if (typeof valueOrUpdater === 'function') {
            newValue = valueOrUpdater(currentValue);
        } else {
            newValue = valueOrUpdater;
        }
        // 应用中间件
        let processedValue = newValue;
        for (const middleware of this.middleware){
            processedValue = middleware(processedValue, currentValue);
        }
        // 如果值没有变化，跳过更新
        if (processedValue === currentValue) {
            return;
        }
        // 保存之前的值
        this.previousValue = currentValue;
        // 通过 Redux action 更新状态
        const action = this.actions.setValue(processedValue);
        this.store.dispatch(action);
        if (this.devMode) {
            console.debug(`[ReduxStateInstance] Updated: ${String(this.id)}`, {
                previous: currentValue,
                current: processedValue,
                action
            });
        }
    }
    /**
   * 订阅状态变化
   */ subscribe(subscriber) {
        if (this.destroyed) {
            throw new Error(`ReduxStateInstance ${String(this.id)} has been destroyed`);
        }
        this.subscribers.add(subscriber);
        if (this.devMode) {
            console.debug(`[ReduxStateInstance] Subscribed: ${String(this.id)}`, {
                subscriberCount: this.subscribers.size
            });
        }
        // 返回取消订阅函数
        return ()=>{
            this.subscribers.delete(subscriber);
            if (this.devMode) {
                console.debug(`[ReduxStateInstance] Unsubscribed: ${String(this.id)}`, {
                    subscriberCount: this.subscribers.size
                });
            }
        };
    }
    /**
   * 获取状态实例标识符
   */ getId() {
        return this.id;
    }
    /**
   * 获取状态作用域
   */ getScope() {
        return this.scope;
    }
    /**
   * 销毁状态实例
   */ destroy() {
        if (this.destroyed) {
            return;
        }
        this.destroyed = true;
        // 取消 Redux store 订阅
        if (this.unsubscribeStore) {
            this.unsubscribeStore();
            this.unsubscribeStore = undefined;
        }
        // 清理订阅者
        this.subscribers.clear();
        if (this.devMode) {
            console.debug(`[ReduxStateInstance] Destroyed: ${String(this.id)}`);
        }
    }
    /**
   * 检查状态实例是否已销毁
   */ isDestroyed() {
        return this.destroyed;
    }
    /**
   * 通知所有订阅者
   */ notifySubscribers() {
        if (this.destroyed) {
            return;
        }
        try {
            const currentValue = this.get();
            // 如果值没有变化，跳过通知
            if (currentValue === this.previousValue) {
                return;
            }
            const previousValue = this.previousValue;
            this.previousValue = currentValue;
            // 使用数组副本避免在迭代过程中修改集合
            const subscribers = Array.from(this.subscribers);
            for (const subscriber of subscribers){
                try {
                    subscriber(currentValue, previousValue);
                } catch (error) {
                    console.error(`[ReduxStateInstance] Error in subscriber for ${String(this.id)}:`, error);
                }
            }
        } catch (error) {
            console.error(`[ReduxStateInstance] Error getting state for ${String(this.id)}:`, error);
        }
    }
    /**
   * 构造函数
   * 
   * @param store - Redux store 实例
   * @param sliceName - Redux slice 名称
   * @param actions - Redux slice actions
   * @param initialValue - 初始状态值
   * @param options - 状态实例配置选项
   */ constructor(store, sliceName, actions, initialValue, options = {}){
        /**
   * 状态实例标识符
   */ _define_property(this, "id", void 0);
        /**
   * 状态作用域
   */ _define_property(this, "scope", void 0);
        /**
   * Redux store 引用
   */ _define_property(this, "store", void 0);
        /**
   * Redux slice 名称（在 store 中的路径）
   */ _define_property(this, "sliceName", void 0);
        /**
   * Redux slice actions
   */ _define_property(this, "actions", void 0);
        /**
   * 订阅者集合
   */ _define_property(this, "subscribers", new Set());
        /**
   * Redux store 订阅取消函数
   */ _define_property(this, "unsubscribeStore", void 0);
        /**
   * 是否已销毁
   */ _define_property(this, "destroyed", false);
        /**
   * 开发模式标志
   */ _define_property(this, "devMode", void 0);
        /**
   * 中间件函数数组
   */ _define_property(this, "middleware", void 0);
        /**
   * 上一次的状态值（用于订阅通知）
   */ _define_property(this, "previousValue", void 0);
        this.store = store;
        this.sliceName = sliceName;
        this.actions = actions;
        this.id = options.id ?? Symbol('ReduxStateInstance');
        this.scope = options.scope;
        this.devMode = options.devMode ?? false;
        this.middleware = options.middleware ?? [];
        this.previousValue = initialValue;
        // 订阅 Redux store 变化
        this.unsubscribeStore = this.store.subscribe(()=>{
            this.notifySubscribers();
        });
        if (this.devMode) {
            console.debug(`[ReduxStateInstance] Created: ${String(this.id)}`, {
                scope: this.scope,
                sliceName: this.sliceName,
                initialValue
            });
        }
    }
};
/**
 * 动态 Reducer 管理器
 * 
 * 用于管理动态添加和移除的 Redux reducer
 */ let DynamicReducerManager = class DynamicReducerManager {
    /**
   * 添加 reducer
   */ addReducer(key, reducer) {
        this.reducers.set(key, reducer);
    }
    /**
   * 移除 reducer
   */ removeReducer(key) {
        this.reducers.delete(key);
    }
    /**
   * 获取根 reducer
   */ getRootReducer() {
        return this.rootReducer;
    }
    /**
   * 检查 reducer 是否存在
   */ hasReducer(key) {
        return this.reducers.has(key);
    }
    /**
   * 构造函数
   */ constructor(){
        /**
   * 当前 reducer 映射
   */ _define_property(this, "reducers", new Map());
        /**
   * 根 reducer 函数
   */ _define_property(this, "rootReducer", void 0);
        this.rootReducer = (state, action)=>{
            const stateRecord = state ?? {};
            const newState = {
                ...stateRecord
            };
            // 处理每个 reducer
            for (const [key, reducer] of this.reducers.entries()){
                newState[key] = reducer(stateRecord[key], action);
            }
            return newState;
        };
    }
};
let ReduxAdapter = class ReduxAdapter {
    /**
   * 检查 Redux 是否可用
   */ checkReduxAvailable() {
    // 这里不抛出错误，允许延迟加载
    // 实际使用时会在 createInstance 时检查
    }
    /**
   * 获取或创建 Redux store
   */ getOrCreateStore() {
        if (this.store) {
            return this.store;
        }
        // 尝试创建 Redux store
        try {
            // 动态导入 Redux Toolkit
            // 注意：这里使用类型断言，实际运行时需要确保 Redux 已安装
            // eslint-disable-next-line @typescript-eslint/no-require-imports
            const { configureStore } = require('@reduxjs/toolkit');
            this.store = configureStore({
                reducer: this.reducerManager.getRootReducer(),
                devTools: this.devMode,
                middleware: undefined
            });
            if (this.devMode) {
                console.debug('[ReduxAdapter] Redux store created');
            }
            return this.store;
        } catch (error) {
            throw new Error('ReduxAdapter requires @reduxjs/toolkit to be installed. ' + 'Please install it: npm install @reduxjs/toolkit\n' + `Original error: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
    /**
   * 创建 Redux slice
   */ createSlice(sliceName, initialValue) {
        try {
            // 动态导入 Redux Toolkit
            // eslint-disable-next-line @typescript-eslint/no-require-imports
            const { createSlice } = require('@reduxjs/toolkit');
            const slice = createSlice({
                name: sliceName,
                initialState: initialValue,
                reducers: {
                    setValue: (_state, action)=>{
                        return action.payload ?? initialValue;
                    }
                }
            });
            return slice;
        } catch (error) {
            throw new Error('ReduxAdapter requires @reduxjs/toolkit to be installed. ' + 'Please install it: npm install @reduxjs/toolkit\n' + `Original error: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
    /**
   * 创建状态实例
   */ createInstance(initialValue, options) {
        if (this.destroyed) {
            throw new Error('ReduxAdapter has been destroyed');
        }
        // 获取或创建 Redux store
        const store = this.getOrCreateStore();
        // 生成唯一的 slice 名称
        const sliceName = options?.id ? `secra_${String(options.id)}` : `secra_slice_${++this.sliceCounter}`;
        // 创建 Redux slice
        const slice = this.createSlice(sliceName, initialValue);
        // 将 slice reducer 添加到动态 reducer 管理器
        if (!this.reducerManager.hasReducer(sliceName)) {
            this.reducerManager.addReducer(sliceName, slice.reducer);
            // 更新 store 的 reducer（使用 replaceReducer）
            store.replaceReducer(this.reducerManager.getRootReducer());
        }
        // 创建状态实例
        const instance = new ReduxStateInstance(store, sliceName, slice.actions, initialValue, {
            id: options?.id,
            scope: options?.scope,
            devMode: options?.devMode ?? this.devMode,
            middleware: options?.middleware
        });
        this.instances.add(instance);
        this.sliceToInstance.set(sliceName, instance);
        if (this.devMode) {
            console.debug(`[ReduxAdapter] Created instance: ${String(instance.getId())}`, {
                sliceName,
                scope: options?.scope
            });
        }
        return instance;
    }
    /**
   * 销毁适配器
   */ destroy() {
        if (this.destroyed) {
            return;
        }
        // 销毁所有创建的状态实例
        for (const instance of this.instances){
            instance.destroy();
        }
        // 从 reducer 管理器中移除所有 reducer
        for (const sliceName of this.sliceToInstance.keys()){
            this.reducerManager.removeReducer(sliceName);
        }
        // 更新 store 的 reducer
        if (this.store) {
            this.store.replaceReducer(this.reducerManager.getRootReducer());
        }
        this.instances.clear();
        this.sliceToInstance.clear();
        this.store = null;
        this.destroyed = true;
        if (this.devMode) {
            console.debug('[ReduxAdapter] Destroyed');
        }
    }
    /**
   * 获取适配器名称
   */ getName() {
        return this.name;
    }
    /**
   * 构造函数
   * 
   * @param options - 适配器配置选项
   */ constructor(options){
        /**
   * 适配器名称
   */ _define_property(this, "name", 'ReduxAdapter');
        /**
   * 是否已销毁
   */ _define_property(this, "destroyed", false);
        /**
   * 创建的状态实例集合
   */ _define_property(this, "instances", new Set());
        /**
   * Redux store 实例
   */ _define_property(this, "store", null);
        /**
   * Redux slice 名称计数器（用于生成唯一的 slice 名称）
   */ _define_property(this, "sliceCounter", 0);
        /**
   * Redux slice 名称到状态实例的映射
   */ _define_property(this, "sliceToInstance", new Map());
        /**
   * 动态 reducer 管理器
   */ _define_property(this, "reducerManager", void 0);
        /**
   * 是否启用开发模式
   */ _define_property(this, "devMode", void 0);
        this.devMode = options?.devMode ?? false;
        this.reducerManager = new DynamicReducerManager();
        this.store = options?.store ?? null;
        // 检查 Redux 是否可用
        this.checkReduxAvailable();
    }
};

//# sourceMappingURL=ReduxAdapter.js.map