//Copyright (c) 2018 蔦森くいな
//http://opensource.org/licenses/mit-license.php
//blog   : http://paradre.com/
//Twitter: https://twitter.com/Kuina_T
/*:
 * @plugindesc 
 * @author 蔦森くいな
 *
 * @help 
 */
(function() {
    Game_Event.prototype.pd_TE_resetPropaty = function() {
        this.__pd_TE.touchTriggerType = 0;
        this.__pd_TE.touchSwitchIndex = ['',''];
        this.__pd_TE.Hash = {};
        this.__pd_TE.triggerDisable = false;
        this.__pd_TE.tag = [];
        this.__pd_TE.ETE_TriggerType = 0;
        this.__pd_TE.ETE_Tag = [];
        this.__pd_TE.ETE_SwitchIndex = ['',''];
        this.__pd_TE.EFE_TriggerType = 0;
        this.__pd_TE.EFE_Tag = [];
        this.__pd_TE.EFE_SwitchIndex = ['',''];
        this.__pd_TE.EFE_exception = false;
        this.__pd_TE.Touch_forceRun = false;
        this.__pd_TE.lastTouchedEvent = null;
        this.__pd_TE.ETR_TriggerType = 0;
        this.__pd_TE.ETR_Num = [];
        this.__pd_TE.ETR_SwitchIndex = ['',''];
    };
    var pd_TE_Game_Event_initialize = Game_Event.prototype.initialize;
    Game_Event.prototype.initialize = function(mapId, eventId) {
        this.__pd_TE = {};
        this.pd_TE_resetPropaty();
        pd_TE_Game_Event_initialize.call(this, mapId, eventId);
    };
    var pd_TE_Game_Map_setupEvents = Game_Map.prototype.setupEvents;
    Game_Map.prototype.setupEvents = function() {
        if($gameMap._pd_TE_EFE_Enable === true){
            $gameMap._pd_TE_EFE_Enable = false;
        }
        pd_TE_Game_Map_setupEvents.call(this);
    };
    var pd_TE_Game_Event_clearPageSettings = Game_Event.prototype.clearPageSettings;
    Game_Event.prototype.clearPageSettings = function() {
        pd_TE_Game_Event_clearPageSettings.call(this);
        this.pd_TE_resetPropaty();
    };
    var pd_TE_Game_Event_setupPageSettings = Game_Event.prototype.setupPageSettings;
    Game_Event.prototype.setupPageSettings = function() {
        pd_TE_Game_Event_setupPageSettings.call(this);
        this.pd_TE_resetPropaty();
        var Command_List = this.list();
        var index = 0;
        while(Command_List[index].code === 108 || Command_List[index].code === 408){
            var command = Command_List[index].parameters[0].toLowerCase().replace(/　/g,' ').split(' ');
            for(var i = 0, len = command.length; i < len; i++){
                var param = command[i].replace(/:/g,',').replace(/：/g,',').split(',');
                var header = param[0].substr(0,1);
                if(header === '#') param[0] = param[0].substr(1);
                switch(param[0]){
                    case 'タッチ':
                    case 'touch':
                        if(param.length > 1){
                            if(header === '#'){
                                this.__pd_TE.touchTriggerType = 2;
                            }else{
                                this.__pd_TE.touchTriggerType = 1;
                            }
                            this.__pd_TE.touchSwitchIndex = this.pd_TE_CheckSwitchIndex(param[1]);
                        }else{
                            this.__pd_TE.touchTriggerType = 1;
                        }
                        break;
                    case 'バルーン': 
                        if (param.length > 1) {
                            this.TCkBlnNo = Number(param[1]); 
                        }
                        break;
                    case '距離': 
                        if (param.length > 1) {
                            this.TCkKyori = Number(param[1]); 
                        }
                        break;
                    case 'タップ':
                    case 'tap':
                        if(param.length > 1){
                            if(header === '#'){
                                this.__pd_TE.touchTriggerType = 4;
                            }else{
                                this.__pd_TE.touchTriggerType = 3;
                            }
                            this.__pd_TE.touchSwitchIndex = this.pd_TE_CheckSwitchIndex(param[1]);
                        }else{
                            this.__pd_TE.touchTriggerType = 3;
                        }
                        break;
                    case 'タグ':
                    case 'tag':
                        if(param.length > 1){
                            for(var j = 1, len2 = param.length; j < len2; j++){
                                this.__pd_TE.tag[j-1] = param[j];
                            }
                        }else{
                            throw new Error('TriggerExtension Plugin : タグに名前が設定されていません');
                        }
                        break;
                    case 'トリガー無効':
                    case 'triggerdisable':
                        this.__pd_TE.triggerDisable = true;
                        break;
                    case 'イベントに接触':
                    case 'toevent':
                        if(param.length > 1){
                            if(header === '#'){
                                this.__pd_TE.ETE_TriggerType = 2;
                            }else{
                                this.__pd_TE.ETE_TriggerType = 1;
                            }
                            this.__pd_TE.ETE_SwitchIndex = this.pd_TE_CheckSwitchIndex(param[1]);
                            if(param.length > 2){
                                for(var j = 2, len2 = param.length; j < len2; j++){
                                    this.__pd_TE.ETE_Tag[j-2] = param[j];
                                }
                            }else{
                                this.__pd_TE.ETE_Tag[0] = '';
                            }
                        }else{
                            this.__pd_TE.ETE_Tag[0] = '';
                        }
                        break;
                    case 'イベントが接触':
                    case 'fromevent':
                        if(param.length > 1){
                            if(header === '#'){
                                this.__pd_TE.EFE_TriggerType = 2;
                            }else{
                                this.__pd_TE.EFE_TriggerType = 1;
                            }
                            this.__pd_TE.EFE_SwitchIndex = this.pd_TE_CheckSwitchIndex(param[1]);
                            $gameMap._pd_TE_EFE_Enable = true;
                            if(param.length > 2){
                                for(var j = 2, len2 = param.length; j < len2; j++){
                                    this.__pd_TE.EFE_Tag[j-2] = param[j];
                                }
                            }else{
                                this.__pd_TE.EFE_Tag[0] = '';
                            }
                        }else{
                            this.__pd_TE.EFE_Tag[0] = '';
                            $gameMap._pd_TE_EFE_Enable = true;
                        }
                        break;
                    case 'リージョンに接触':
                    case 'toregion':
                        if(param.length > 1){
                            if(header === '#'){
                                this.__pd_TE.ETR_TriggerType = 2;
                            }else{
                                this.__pd_TE.ETR_TriggerType = 1;
                            }
                            this.__pd_TE.ETR_SwitchIndex = this.pd_TE_CheckSwitchIndex(param[1]);
                            if(param.length > 2){
                                for(var j = 2, len2 = param.length; j < len2; j++){
                                    this.__pd_TE.ETR_Num[j-2] = param[j];
                                }
                            }else{
                                this.__pd_TE.ETR_Num[0] = '';
                            }
                        }else{
                            this.__pd_TE.ETR_Num[0] = '';
                        }
                        break;
                    case '除外':
                    case 'exception':
                        this.__pd_TE.EFE_exception = true;
                        break;
                    case '強制実行':
                    case 'forcerun':
                        this.__pd_TE.Touch_forceRun = true;
                        break;
                }
            }
            index = index + 1;
        }
    };
    Game_Event.prototype.pd_TE_CheckSwitchIndex = function(switchIndex) {
        if(isNaN(switchIndex)){
            if(switchIndex === ''){
                return ['', ''];
            }
            else if(switchIndex.contains('=')){
                switchIndex = switchIndex.split('=');
                if(switchIndex.length > 2){
                    throw new Error('TriggerExtension Plugin : 「=」の数が多すぎます');
                }else{
                    return switchIndex;
                }
            }
            else if(switchIndex === 'a' || switchIndex === 'b' || switchIndex === 'c' || switchIndex === 'd'){
                return ['SelfSwitch', switchIndex.toUpperCase()];
            }else{
                throw new Error('TriggerExtension Plugin : セルフスイッチに指定できる文字はA,B,C,Dだけです : ['+switchIndex.toUpperCase()+']');
            }
        }else{
            return ['Switch', switchIndex];
        }
    };
    var pd_TE_Game_Event_update = Game_Event.prototype.update;
    Game_Event.prototype.update = function() {
        pd_TE_Game_Event_update.call(this);
        if (!$gameMap.isEventRunning()) {
            if (this.pd_TE_CheckTouchEvent()) {
                this.pd_TE_SetSwitchIndex(this.__pd_TE.touchSwitchIndex);
                if (this.__pd_TE.touchTriggerType === 1 || this.__pd_TE.touchTriggerType === 3) {
                    this.start('pd_TE_enable');
                    this.unlock(false);
                }
            }
        }
    };
    Game_Event.prototype.pd_TE_CheckTouchEvent = function() {
        if(this.__pd_TE.touchTriggerType >= 3){
            if (TouchInput.isTriggered()) {
                if($gameTemp._pd_TE_realTouchMapX >= this._realX && $gameTemp._pd_TE_realTouchMapX < this._realX + 1 &&
                  $gameTemp._pd_TE_realTouchMapY >= this._realY && $gameTemp._pd_TE_realTouchMapY < this._realY + 1){
                    $gameTemp._pd_TE_touchTriggerTime = Date.now();
                }
            }else if(TouchInput.isReleased() && Date.now() - $gameTemp._pd_TE_touchTriggerTime <= 500){
                if($gameTemp._pd_TE_realTouchMapX >= this._realX && $gameTemp._pd_TE_realTouchMapX < this._realX + 1 &&
                  $gameTemp._pd_TE_realTouchMapY >= this._realY && $gameTemp._pd_TE_realTouchMapY < this._realY + 1){
                    $gameTemp._pd_TE_touchTriggerTime = 0;
                    return true;
                }
            }
        }
        else if(this.__pd_TE.touchTriggerType >= 1){
            if (TouchInput.isTriggered()) {
                if($gameTemp._pd_TE_realTouchMapX >= this._realX && $gameTemp._pd_TE_realTouchMapX < this._realX + 1 &&
                  $gameTemp._pd_TE_realTouchMapY >= this._realY && $gameTemp._pd_TE_realTouchMapY < this._realY + 1){
                    return true;
                }
            }
        }
        return false;
    };
    var pd_TE_Game_Event_start = Game_Event.prototype.start;
    Game_Event.prototype.start = function() {
        if(this.__pd_TE.triggerDisable && arguments[0] != 'pd_TE_enable'){
            return;
        }
        pd_TE_Game_Event_start.call(this);
    };
    var pd_TE_Game_Event_moveStraight = Game_Event.prototype.moveStraight;
    Game_Event.prototype.moveStraight = function(d) {
        var _pd_TE_x = $gameMap.roundXWithDirection(this._x, d);
        var _pd_TE_y = $gameMap.roundYWithDirection(this._y, d);
        pd_TE_Game_Event_moveStraight.call(this, d);
        if(this.__pd_TE.ETE_Tag.length >= 1 ||
           ($gameMap._pd_TE_EFE_Enable === true && this.__pd_TE.EFE_exception === false)){
            $gameMap.eventsXy(_pd_TE_x, _pd_TE_y).forEach(function(event) {
                if(event != this){
                    if (this.__pd_TE.ETE_Tag.length >= 1 && (this.__pd_TE.ETE_Tag[0] === '' || this.pd_TE_CheckTag(this.__pd_TE.ETE_Tag, event.__pd_TE.tag))) {
                        this.pd_TE_EventTouchEvent_Start(this, this.__pd_TE.ETE_SwitchIndex, event, this.__pd_TE.ETE_TriggerType);
                    }
                    else if($gameMap._pd_TE_EFE_Enable === true && event.__pd_TE.EFE_Tag.length >= 1 && this.__pd_TE.EFE_exception === false && (event.__pd_TE.EFE_Tag[0] === '' || this.pd_TE_CheckTag(this.__pd_TE.tag, event.__pd_TE.EFE_Tag))){
                        this.pd_TE_EventTouchEvent_Start(event, event.__pd_TE.EFE_SwitchIndex, this, event.__pd_TE.EFE_TriggerType);
                    }
                }
            } , this);
        }
        if (this.__pd_TE.ETR_Num.length >= 1 && (!$gameMap.isEventRunning() || this.__pd_TE.Touch_forceRun === true) && this.pd_TE_CheckRegionId(this.__pd_TE.ETR_Num, _pd_TE_x, _pd_TE_y)) {
            if (!this.isJumping()) {
                this.pd_TE_SetSwitchIndex(this.__pd_TE.ETR_SwitchIndex);
                if(this.__pd_TE.ETR_TriggerType === 1){
                    this.start('pd_TE_enable');
                    this.unlock(false);
                }
            }
        }
    };
    Game_Event.prototype.pd_TE_CheckTag = function(tagList1, tagList2) {
        for(var i = 0, len = tagList1.length; i < len; i++){
            for(var j = 0, len2 = tagList2.length; j < len2; j++){
                if(tagList1[i] === tagList2[j]) return true;
            }
        }
        return false;
    };
    Game_Event.prototype.pd_TE_CheckRegionId = function(regionList, x, y) {
        var reg = $gameMap.regionId(x, y);
        if(regionList[0] === ''){
            if(reg >= 1) return true;
        }else{
            for(var i = 0, len = regionList.length; i < len; i++){
                if(regionList[i] == reg) return true;
            }
        }
        return false;
    };
    Game_Event.prototype.pd_TE_EventTouchEvent_Start = function(obj, indexVar, touchEvent, triggerType) {
        if (!$gameMap.isEventRunning() || obj.__pd_TE.Touch_forceRun === true) {
            if (!obj.isJumping()) {
                obj.__pd_TE.lastTouchedEvent = touchEvent;
                obj.pd_TE_SetSwitchIndex(indexVar);
                if(triggerType === 1){
                    obj.start('pd_TE_enable');
                    obj.unlock(false);
                }
            }
        }
    };
    Game_Event.prototype.pd_TE_SetSwitchIndex = function(indexVar) {
        if(indexVar[0] === ''){
        }
        else if(indexVar[0] === 'Switch'){
            $gameSwitches.setValue(indexVar[1], true);
        }
        else if(indexVar[0] === 'SelfSwitch'){
            $gameSelfSwitches.setValue([this._mapId, this.eventId(), indexVar[1]], true);
        }
        else if(indexVar[0].substr(0,1) === 'v'){
            if(isNaN(indexVar[1])){
                $gameVariables.setValue(parseInt(indexVar[0].substr(1)), indexVar[1]);
            }else{
                $gameVariables.setValue(parseInt(indexVar[0].substr(1)), parseInt(indexVar[1]));
            }
        }
        else{
            this.__pd_TE.Hash[indexVar[0]] = indexVar[1];
        }
    }
    var pd_TE_Game_Temp_initialize = Game_Temp.prototype.initialize;
    Game_Temp.prototype.initialize = function() {
        pd_TE_Game_Temp_initialize.call(this);
        this._pd_TE_realTouchMapX = null;
        this._pd_TE_realTouchMapY = null;
        this._pd_TE_touchTriggerTime = 0;
    };
    var pd_TE_Game_Map_initialize = Game_Map.prototype.initialize;
    Game_Map.prototype.initialize = function() {
        pd_TE_Game_Map_initialize.call(this);
        this._pd_TE_EFE_Enable = false;
    };
    var pd_TE_Scene_Map_update = Scene_Map.prototype.update;
    Scene_Map.prototype.update = function() {
        if (TouchInput.isPressed()) {
            $gameTemp._pd_TE_realTouchMapX = ($gameMap._displayX * $gameMap.tileWidth() + TouchInput.x) / $gameMap.tileWidth();
            $gameTemp._pd_TE_realTouchMapY = ($gameMap._displayY * $gameMap.tileHeight() + TouchInput.y) / $gameMap.tileHeight();
        }
        pd_TE_Scene_Map_update.call(this);
        if(TouchInput.isReleased()){
            $gameTemp._pd_TE_realTouchMapX = null;
            $gameTemp._pd_TE_realTouchMapY = null;
        }
    };
})();
