/**
 * 数据中心类
 */

import EventEmitter from "./EventEmitter";
import {utils} from "../tools";

export default class DataCenter extends EventEmitter {
	private store: any = {};

	/**
	 * 注册一个数据根
	 * @param type
	 */
	public register(type: string) {
		this.store[type] = this.store[type] || {};
	}

	/**
	 * 清空数据，如果type为false值，就清空整个数据中心
	 * @param type
	 */
	public clean(type?: string) {
		let target = type ? this.store[type] : this.store;
		if (target) {
			let keys = Object.keys(target);
			for (let key of keys) {
				delete target[key];
			}
		}
	}

	/**
	 * 设置数据
	 * @param type
	 * @param key
	 * @param value
	 */
	public set(type: string, key: string, value?) {
		if (arguments.length <= 2) {
			//if (this.store[type]) console.warn(`This operation will override all ${this.store[type]}`);
			this.store[type] = key;
		} else {
			this.store[type][key] = value;
		}
	}

	/**
	 * 获取数据
	 * @param type
	 * @param key
	 */
	public get(type: string, key?: string) {
		if (!key) return this.store[type];
		return this.store[type][key];
	}

	public use(type: string, key: string) {
		return resopnse => {
			this.set(type, key, resopnse);
			return resopnse
		}
	}

	/**
	 * 转换成真实数据
	 * @param type
	 * @param expression
	 */
	public parse(type: string, expression: string) {
		let entity = this.store[type];

		let result = null;
		try {
			result = utils.dotEval(expression, entity);
		} catch (e) {

		}
		return result;
	}
}
