import{KEY_DICT,MULTI_KEYS,MULTI_KEY_CODES}from"./key.dict.js";function bind(e,_){return(e||document).addEventListener("keydown",_,!1),_}function unbind(e,_){(e||document).removeEventListener("keydown",_,!1)}function hide(e,_,t){Object.defineProperty(e,_,{value:t,writable:!0,enumerable:!1,configurable:!0})}function check(e){var _=!1;if(_="object"==typeof this.keys.key?this.keys.key.includes(e.keyCode):e.keyCode===this.keys.key)for(let t in this.keys)if(e[t]!==this.keys[t]){_=!1;break}return _}export default class Keyboard{constructor(e){this.$elem=e,hide(this,"__EVENTS__",{}),hide(this,"paused",!1),hide(this,"__finally__",null),hide(this,"_keydown",bind(e,e=>{if(!this.paused&&!MULTI_KEY_CODES.includes(e.keyCode)){for(let n in this.__EVENTS__){var _=this.__EVENTS__[n],t=_.check(e),i=Date.now(),s=!1;if(!0===_.actived)if(i-_.last>300)delete _.actived;else for(let t of _.next){if(t.check(e)){s=!0,t.fn.forEach(function(_){_(e)});break}}if(t&&(s=!0,_.next&&(_.actived=!0,_.last=i),_.fn&&_.fn.forEach(function(_){_(e)})),s)break}this.__finally__&&this.__finally__(e)}}))}get disabled(){return this.paused}set disabled(e){this.paused=!!e}destroy(){unbind(this.$elem,this._keydown),delete this.__EVENTS__,delete this._keydown}__parse_action__(e){var _=[],t=[],i=!0;return e.forEach(e=>{var s={};e=e.split("+").map(_=>(_=_.trim().toLowerCase(),MULTI_KEYS[_]?s[`${_}Key`]?(i=!1,console.error("功能键,同组中不能重复。⎣%s⎤",e)):s[`${_}Key`]=!0:s.key?(i=!1,console.error("非功能键,同组不能出现多个。⎣%s⎤",e)):hide(s,"key",KEY_DICT[_]),_));for(let e in MULTI_KEYS)s[`${e}Key`]=s[`${e}Key`]||!1;t.push(s),_.push(e.join("+"))}),{keys:_,dict:t,passed:i}}off(e,_){if(e.length<1||"function"!=typeof _)return console.error("无效热键或回调");let{keys:t,dict:i,passed:s}=this.__parse_action__(e);if(s){let e=t[0];if(1===t.length){if(this.__EVENTS__[e]&&this.__EVENTS__[e].fn){let t=0;for(let i of this.__EVENTS__[e].fn){if(i===_){this.__EVENTS__[e].fn.splice(t,1),this.__EVENTS__[e].fn.length<1&&(delete this.__EVENTS__[e].fn,this.__EVENTS__[e].next||delete this.__EVENTS__[e]);break}t++}}}else if(this.__EVENTS__[e]&&this.__EVENTS__[e].next){let i,s=t[1],n=0;for(i of this.__EVENTS__[e].next){if(i.id===s)break;n++}if(i.fn){let t=0;for(let s of i.fn)s===_&&(i.fn.splice(t,1),i.fn.length<1&&(this.__EVENTS__[e].next.splice(n,1),this.__EVENTS__[e].next.length<1&&(delete this.__EVENTS__[e].next,this.__EVENTS__[e].fn||delete this.__EVENTS__[e]))),t++}}}}on(e,_){if(e.length<1||"function"!=typeof _)return console.error("无效热键或回调");let{keys:t,dict:i,passed:s}=this.__parse_action__(e);if(s){let e=t.shift(),s=t.shift();if(this.__EVENTS__[e]||(this.__EVENTS__[e]={id:e,keys:i[0],last:0,check:check}),s){if(this.__EVENTS__[e].next)for(let t,i=-1;t=this.__EVENTS__[e].next[++i];)if(t.id===s)return void t.fn.push(_);this.__EVENTS__[e].next=[{id:s,keys:i[1],check:check,fn:[_]}]}else this.__EVENTS__[e].fn?this.__EVENTS__[e].fn.push(_):this.__EVENTS__[e].fn=[_]}}finally(e){"function"==typeof e&&(this.__finally__=e)}};