/*:
 * @plugindesc 纸娃娃&菜单、装备界面、插件命令显示纸娃娃。使用方法请看右上角的帮助。（*注：路径、文件名请不要使用空格）
 * @author JTK
 * 
 * @param <常规>
 * @default
 *
 * @param Path
 * @desc 图像的路径
 * @default img/material/
 *
 * @param Default Layer ID
 * @desc 当未设置图层时，默认使用的图层编号。
 * @default 1
 * 
 * @help 
 *非公开插件,未得到授权禁止使用!
 *插件联系人:QQ:763992443 或 gmail: silentisbaka
**/

(function() {

    var PARAMETERS = PluginManager.parameters('JTK_Material');
    var PARAM_Material = {
        Path :                String(PARAMETERS['Path'] || 'img/material/'),
        DefaultLayerID :      Number(PARAMETERS['Default Layer ID'] || 1)
    };

    ImageManager.loadMaterial = function(filename, hue) {
        return this.loadBitmap(PARAM_Material.Path, filename, hue, true);
    };

    function Material() {
        this.initialize.apply(this, arguments);
    }

    Material.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
    Material.prototype.constructor = Material;

    Material.prototype.initialize = function() {
        PIXI.DisplayObjectContainer.call(this);
        this._width = 0;
        this._height = 0;
        this._autoadap = [];
        this._mirror = false;
        this._material = [];
        this._cacheBitmaps = [];
        this._paintReady = false;
        this._actorId = 0;

        this._layer = new Sprite();
        this.addChild(this._layer);
    };

    Material.prototype.updateTransform = function() {
        if (this._paintReady) {
            var isReady = true;
            for (var i = 0; i < this._cacheBitmaps.length; i++) {
                if (!this._cacheBitmaps[i].isReady()) {
                    isReady = false;
                    break;
                }
            }
            if (isReady) {
                this._paint();
                this._paintReady = false;
            }
        }
        PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
    };

    Material.prototype._paint = function() {
        if (this._cacheBitmaps[0] == null)
            return;
        var w = this._cacheBitmaps[0].width;
        var h = this._cacheBitmaps[0].height;

        if (this._layer.bitmap)
        {
            this._layer.bitmap.clear();
            this._layer.bitmap.resize(w, h);
        }
        else {
            this._layer.bitmap = new Bitmap(w, h);
            this._layer.bitmap.smooth = true;
        }

        for (var i = 0; i < this._cacheBitmaps.length; i++) {
            bitmap = this._cacheBitmaps[i];
            this._layer.bitmap.blt(bitmap, 0, 0, w, h, 0, 0, w, h);
        }

        this._width = w;
        this._height = h;

        if (this._autoadap.length > 0) {
            var ox = 0;
            var oy = 0;
            var ot = this._autoadap[0];
            var op = this._autoadap[1];
            var sbh = this._autoadap[2];
            var scale = (sbh > 0 ? sbh / this._height : 1);
            switch (ot) {
            case 7:     break;
            case 8:     ox=this._width/2;break;
            case 9:     ox=this._width;break;

            case 4:     oy=this._height/2;break;
            case 5:     ox=this._width/2;oy=this._height/2;break;
            case 6:     ox=this._width;oy=this._height/2;break;

            case 1:     oy=this._height;break;
            case 2:     ox=this._width/2;oy=this._height;break;
            case 3:     ox=this._width;oy=this._height;break;
            default:
            }
            this.x = op[0] - ox * scale;
            this.y = op[1] - oy * scale;
            this.scale.x = scale;
            this.scale.y = scale;
            this._layer.anchor.x = 0.5;
            this._layer.anchor.y = 0.5;
            this._layer.x = this._width * this._layer.anchor.x;
            this._layer.y = this._height * this._layer.anchor.y;
            this._layer.scale.x = scale * (this._mirror ? -1 : 1);
            this._layer.scale.y = scale;
        }
    };

    Material.prototype.autoadap = function(originType, originPoint, scaleByHeight) {
        this._autoadap = [originType, originPoint, scaleByHeight];
    };

    Material.prototype.refresh = function() {
        this._cacheBitmaps.length = 0;
        for (var i = 0; i < this._material.length; i++) {
            var bitmap = ImageManager.loadMaterial(this._material[i]);
            this._cacheBitmaps.push(bitmap);
        }
        this._paintReady = true;
        if (this._layer.bitmap)
            this._layer.bitmap.clear();
    };

    Material.prototype.loadActor = function(actorId) {
        this._actorId = actorId;
        this._material = [];
        var material_layers = [];
        var actor = $dataActors[actorId];

        // Body
        var note = actor.note;
        var body = this._readNote(note);
        for (var i = 0; i < body.length; i++) {
            if (body[i] == null)
                continue;
            if (material_layers[i] == null)
                material_layers[i] = [];
            for (var j = 0; j < body[i].length; j++) {
                material_layers[i].push(body[i][j]);
            }
        }

        // Armor
        var armors = $gameActors.actor(actorId).armors();
        for (var i = 0; i < armors.length; i++) {
            var note = armors[i].note;
            var armor = this._readNote(note);
            for (var j = 0; j < armor.length; j++) {
                if (armor[j] == null)
                    continue;
                if (material_layers[j] == null)
                    material_layers[j] = [];
                for (var k = 0; k < armor[j].length; k++) {
                    material_layers[j].push(armor[j][k]);
                }
            }
        }

        // Weapon
        var weapons = $gameActors.actor(actorId).weapons();
        for (var i = 0; i < weapons.length; i++) {
            var note = weapons[i].note;
            var weapon = this._readNote(note);
            for (var j = 0; j < weapon.length; j++) {
                if (weapon[j] == null)
                    continue;
                if (material_layers[j] == null)
                    material_layers[j] = [];
                for (var k = 0; k < weapon[j].length; k++) {
                    material_layers[j].push(weapon[j][k]);
                }
            }
        }

        // concat
        for (var i = 0; i < material_layers.length; i++) {
            if (material_layers[i] == null)
                continue;
            for (var j = 0; j < material_layers[i].length; j++) {
                this._material.push(material_layers[i][j]);
            }
        }
    };

    Material.prototype._readNote = function(note) {
        var material_layers = [];
        var lines = note.split(' ').join('').split('\n');

        for (var i = 0; i < lines.length; i++) {
            var datas = lines[i].split('<material>');
            if (datas.length < 2)
                continue;
            if (datas[1].length == 0)
                continue;

            var data = datas[1].split('||');
            var result = '';
            var layer = PARAM_Material.DefaultLayerID;
            for (var j = 0; j < data.length; j++) {
                var str = data[j];
                var checkSub = str.split('');
                if (checkSub[0] == '\\') {
                    if (checkSub[1] == 'L') {
                        var vid = parseInt(checkSub.join('').substring(3, checkSub.length - 1));
                        layer = vid;
                        continue;
                    }
                    if (checkSub[1] == 'V') {
                        var vid = parseInt(checkSub.join('').substring(3, checkSub.length - 1));
                        var variable = $gameVariables.value(vid);
                        if (variable.constructor === String) {
                            result = variable;
                            continue;
                        }
                    }
                    if (checkSub[1] == 'C') {
                        var sub = checkSub.join('').split(':');
                        var vid = parseInt(sub[0].substring(3, sub[0].split('').length - 1));
                        if (this._actorId == vid) {
                            if (sub[1].length > 0){
                                result = sub[1];
                                continue;
                            }
                            else
                                break;
                        }
                    }
                }
                else {
                    if (result.length == 0)
                        result = str;
                    break;
                }
            }
            if (material_layers[layer] == null)
                material_layers[layer] = [];
            material_layers[layer].push(result);
        }

        return material_layers;
    };



    Window_MenuCommand.prototype.addFormationCommand = function() {};



    var Material_Scene_Menu_create = Scene_Menu.prototype.create;
    Scene_Menu.prototype.create = function() {
        Material_Scene_Menu_create.call(this);
        this.createMaterial();
    };

    Scene_Menu.prototype.start = function() {
        Scene_MenuBase.prototype.start.call(this);
        this._material.loadActor(1);
        this._material.refresh();
    };

    Scene_Menu.prototype.createMaterial = function() {
        this._material = $gameTemp._material || new Material();
        this._material.autoadap(9, [Graphics.width, 0], Graphics.height);
        this.addChild(this._material);
    };

    Scene_Menu.prototype.createCommandWindow = function() {
        this._commandWindow = new Window_MenuCommand(0, 0);
        this._commandWindow.setHandler('item',      this.commandItem.bind(this));
        // No party selecting.
        this._commandWindow.setHandler('skill',     this.commandSkill.bind(this));
        this._commandWindow.setHandler('equip',     this.commandEquip.bind(this));
        this._commandWindow.setHandler('status',    this.commandStatus.bind(this));

        //this._commandWindow.setHandler('skill',     this.commandPersonal.bind(this));
        //this._commandWindow.setHandler('equip',     this.commandPersonal.bind(this));
        //this._commandWindow.setHandler('status',    this.commandPersonal.bind(this));
        //this._commandWindow.setHandler('formation', this.commandFormation.bind(this));

        this._commandWindow.setHandler('options',   this.commandOptions.bind(this));
        this._commandWindow.setHandler('save',      this.commandSave.bind(this));
        this._commandWindow.setHandler('gameEnd',   this.commandGameEnd.bind(this));
        this._commandWindow.setHandler('cancel',    this.popScene.bind(this));
        this.addWindow(this._commandWindow);
    };

    Scene_Menu.prototype.createStatusWindow = function() {};

    Scene_Menu.prototype.commandSkill = function() {
        SceneManager.push(Scene_Skill);
    };

    Scene_Menu.prototype.commandEquip = function() {
        SceneManager.push(Scene_EquipM);
        $gameTemp._material = this._material;
    };

    Scene_Menu.prototype.commandStatus = function() {
        SceneManager.push(Scene_Status);
    };



    function Scene_EquipM() {
        this.initialize.apply(this, arguments);
    }

    Scene_EquipM.prototype = Object.create(Scene_MenuBase.prototype);
    Scene_EquipM.prototype.constructor = Scene_EquipM;

    Scene_EquipM.prototype.initialize = function() {
        Scene_MenuBase.prototype.initialize.call(this);
    };

    Scene_EquipM.prototype.create = function() {
        Scene_Base.prototype.create.call(this);
        this.createBackground();
        this.updateActor();
        this.createMaterial();
        this.createWindowLayer();

        this.createHelpWindow();
        this.createSlotWindow();
        this.createItemWindow();
        this.refreshActor();
    };

    Scene_EquipM.prototype.createMaterial = function() {
        this._material = $gameTemp._material || new Material();
        this.addChild(this._material);
    };

    Scene_EquipM.prototype.createHelpWindow = function() {
        Scene_MenuBase.prototype.createHelpWindow.call(this);
        this._helpWindow.y = Graphics.boxHeight - this._helpWindow.height;
        this._helpWindow.visible = false;
    };

    Scene_EquipM.prototype.createSlotWindow = function() {
        var wx = 0;
        var wy = 0;
        var ww = 400;
        var wh = 224;
        this._slotWindow = new Window_EquipSlot(wx, wy, ww, wh);
        this._slotWindow.setHelpWindow(this._helpWindow);
        this._slotWindow.setHandler('ok',       this.onSlotOk.bind(this));
        this._slotWindow.setHandler('cancel',   this.popScene.bind(this));
        this._slotWindow.activate();
        this._slotWindow.select(0);
        this.addWindow(this._slotWindow);
    };

    Scene_EquipM.prototype.createItemWindow = function() {
        var wx = 0;
        var wy = this._slotWindow.y + this._slotWindow.height;
        var ww = Graphics.boxWidth;
        var wh = this._helpWindow.y - wy;
        this._itemWindow = new Window_EquipItem(wx, wy, ww, wh);
        this._itemWindow.setHelpWindow(this._helpWindow);
        this._itemWindow.setHandler('ok',     this.onItemOk.bind(this));
        this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this));
        this._itemWindow.visible = false;
        this._slotWindow.setItemWindow(this._itemWindow);
        this.addWindow(this._itemWindow);
    };

    Scene_EquipM.prototype.refreshActor = function() {
        var actor = this.actor();
        this._slotWindow.setActor(actor);
        this._itemWindow.setActor(actor);
        this._material.loadActor(actor._actorId);
        this._material.refresh();
    };

    Scene_EquipM.prototype.onSlotOk = function() {
        this._helpWindow.visible = true;
        this._itemWindow.visible = true;
        this._itemWindow.activate();
        this._itemWindow.select(0);
    };

    Scene_EquipM.prototype.onItemOk = function() {
        SoundManager.playEquip();
        this.actor().changeEquip(this._slotWindow.index(), this._itemWindow.item());
        this._slotWindow.activate();
        this._slotWindow.refresh();
        this._itemWindow.deselect();
        this._itemWindow.refresh();
        this._helpWindow.visible = false;
        this._itemWindow.visible = false;
        this._material.loadActor(this.actor()._actorId);
        this._material.refresh();
    };

    Scene_EquipM.prototype.onItemCancel = function() {
        this._slotWindow.activate();
        this._itemWindow.deselect();
        this._helpWindow.visible = false;
        this._itemWindow.visible = false;
    };



    var Material_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
    Game_Interpreter.prototype.pluginCommand = function(command, args) {
        Material_Game_Interpreter_pluginCommand.call(this, command, args);
        if (command == 'Material') {
            var id = $gameTemp._materialId || 1;
            var pos = $gameTemp._materialPos || 'right';
            var mirror = $gameTemp._materialMirror || false;
            var fade = $gameTemp._materialFade || 1;
            var off = false;
            for (var i = 0; i < args.length; i++) {
                arg = args[i];
                switch (arg) {
                case 'off':
                    off = true;
                    break;
                default:
                    cmd = arg.split('=');
                    switch (cmd[0]) {
                    case 'id':
                        id = parseInt(cmd[1]);
                        break;
                    case 'pos':
                        pos = cmd[1];
                        break;
                    case 'mirror':
                        mirror = (cmd[1] == 'true' ? true : false);
                        break;
                    case 'fade':
                        fade = parseInt(cmd[1]);
                        break;
                    default:
                    }
                }
            }
            $gameTemp._materialId = id;
            $gameTemp._materialPos = pos;
            $gameTemp._materialMirror = mirror;
            $gameTemp._materialFade = fade;
            $gameTemp._materialOn = !off;
            $gameTemp._materialOnMapChanged = null;
        }
    };



    var Material_Scene_Map_createWindowLayer = Scene_Map.prototype.createWindowLayer;
    Scene_Map.prototype.createWindowLayer = function() {
        this._material = new Material();
        this._material.visible = false;
        this.addChild(this._material);
        $gameTemp._materialOpacity = 0;
        Material_Scene_Map_createWindowLayer.call(this);
    };

    var Material_Scene_Map_update = Scene_Map.prototype.update;
    Scene_Map.prototype.update = function() {
        Material_Scene_Map_update.call(this);

        var id = $gameTemp._materialId;
        var pos = $gameTemp._materialPos;
        var mirror = $gameTemp._materialMirror;
        var fade = $gameTemp._materialFade;
        var opacity = $gameTemp._materialOpacity;

        if ($gameTemp._materialOn) {
            if ($gameTemp._materialOnMapChanged != $gameTemp._materialOn) {
                $gameTemp._materialOnMapChanged = $gameTemp._materialOn;
                this._material.loadActor(id);
                this._material.refresh();
                this._material.visible = true;
                opacity = (fade > 1 ? 0 : 255);

                switch (pos) {
                case 'left':
                    this._material.autoadap(7, [0, 0], Graphics.height);
                    break;
                case 'center':
                    this._material.autoadap(8, [Graphics.width/2, 0], Graphics.height);
                    break;
                case 'right':
                    this._material.autoadap(9, [Graphics.width, 0], Graphics.height);
                    break;
                default:
                }
                this._material._mirror = mirror;
            }

            if (opacity <= 254)
                opacity += (255 - opacity) / (fade > 1 ? fade : 1);
            else
                opacity = 255;
        }
        else {
            if (opacity >= 1) {
                opacity += (0 - opacity) / (fade > 1 ? fade : 1);
                if (fade <= 1)
                    opacity = 0;
            }
            else {
                if ($gameTemp._materialOnMapChanged != $gameTemp._materialOn) {
                    $gameTemp._materialOnMapChanged = $gameTemp._materialOn;
                    this._material.visible = false;
                    opacity = 0;
                }
            }
        }

        this._material._layer.opacity = opacity;
        $gameTemp._materialOpacity = opacity;
    };


})();
