export class KeyEventManager {
	stateManager: any
	layerManager: any
	onWorkbench: any
	constructor(options) {
		this.stateManager = options.stateManager;
		this.layerManager = options.layerManager;
		this.onWorkbench = options.onWorkbench;
		this._handleKeyDown = this.handleKeyDown.bind(this)
		this._handlePaste = this.handlePaste.bind(this)
	}
	onMounted() { }
	/** 注册事件 */
	registerEvents() {
		document.addEventListener('keydown', this._handleKeyDown)
		document.addEventListener("paste", this._handlePaste);
	}
	/** 删除事件 */
	removeEvents() {
		document.removeEventListener('keydown', this._handleKeyDown)
		document.removeEventListener("paste", this._handlePaste)
	}

	/** 处理键盘事件 */
	_handleKeyDown: any
	handleKeyDown(event: any) {
		const activeID = this.layerManager.activeID.value
		const ctrl = event.ctrlKey ? 'ctrl-' : "";
		const shift = event.shiftKey ? 'shift-' : "";
		const key = event.key;
		const reg = new RegExp(`^${ctrl}${shift}${key}$`, 'i')
		const list = [
			{ key: "ctrl-c", handler: () => this.layerManager.copyLayerById(activeID) },
			{ key: "delete", handler: () => this.layerManager.deleteLayerById(activeID) },
			{ key: "ctrl-z", handler: () => this.stateManager.undoState() },
			{ key: "ctrl-s", handler: () => this.onWorkbench() },
			{ key: "ctrl-shift-z", handler: () => this.stateManager.redoState() },
		]
		if (list.some((v) => reg.test(v.key))) event.preventDefault()
		list.forEach((v: any) => {
			if (reg.test(v.key)) v.handler(event)
		})
	}
	/** 处理粘贴事件 */
	_handlePaste: any
	handlePaste(event: any) {
		event.preventDefault(); // 阻止默认粘贴行为
		const text = event.clipboardData?.getData("text/plain") || "";
		if (/^aida_copy_canvas_layer/.test(text)) return;
		const items = event.clipboardData?.items || [];
		for (const item of items) {
			if (item.type.indexOf("text/plain") !== -1) {
				item.getAsString((text) => {
					console.log('粘贴文本', text);
				});
			} else if (item.type.indexOf("image") !== -1) {
				const file = item.getAsFile();
				this.layerManager.createFileImageLayer(file, false).then(layer => {
					const id = layer?.info?.id
					this.stateManager.objectManager.setFillRepeat(id)
				})
			}
		}
	}
	/** 销毁事件管理器 */
	dispose() {
		this.removeEvents()
	}
}
