'use strict';

goog.provide('Blockly.Blocks.blynk');
goog.require('Blockly.Blocks');

Blockly.Blocks.blynk.hue="#3a545a";

Blockly.Blocks['blynk_setup'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("./../blockly/media/blynk_header.png", 150, 60, "15"));
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_SETUP)
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_AUTH)
            .appendField(new Blockly.FieldTextInput("YourAuthToken"),"AUTH")
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_WIFI)
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_SSID)
            .appendField(new Blockly.FieldTextInput("CocoRobo"),"SSID")
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_PW)
            .appendField(new Blockly.FieldTextInput("CocoRobo"),"PW")
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    onchange: function() {
        let len = this.getFieldValue("PW").length;
        if (len > 0) {
            if (len > 20) {
                this.setWarningText(Blockly.Msg.WIFINETWORK_PW_WARN, 'blynk_pw');
            } else {
                this.setWarningText(null, 'blynk_pw');
            }
        } else if (len == 0) {
            if (len == 0) this.setFieldValue("cocorobo", "PW");
        }
        /** set limitation of AUTH input length */
        var text_content = this.getFieldValue("AUTH");
        if (text_content.length > 50) {
          this.setFieldValue(text_content.substring(0,50),"AUTH")
        }
        /** set limitation of SSID input length */
        var text_content = this.getFieldValue("SSID");
        if (text_content.length > 20) {
          this.setFieldValue(text_content.substring(0,20),"SSID")
        }
        /** set limitation of PW input length */
        var text_content = this.getFieldValue("PW");
        if (text_content.length > 20) {
          this.setFieldValue(text_content.substring(0,20),"PW")
        }
    }
};


/**
 *
 */
Blockly.Blocks['blynk_write'] = {
    /**
     * Block for creating a digtial pin selector.
     * @this Blockly.Block
     */
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("./../blockly/media/blynk_header_down.png", 150, 60, "15"));
        // this.appendDummyInput()
        //     .appendField("BLYNK WRITE")
        this.appendDummyInput()
            .appendField(" "+ Blockly.Msg.BLYNK_SELECT)
            .appendField(new Blockly.FieldDropdown([
                ["Button","Button"],
                ["Slider","Slider"],
                ["Joystick","Joystick"],
                ["zeRGBa","zeRGBa"],
                ["Step","Step"],    
                ["Light(sensor)","Light"],
                ["Gravity(sensor)","Gravity"],
                ["Accelerometer(sensor)","Accelerometer"],        
                ["GPS(sensor)","GPS"],                               
            ]),"MOD")
        this.appendDummyInput()
            .appendField(" "+Blockly.Msg.BLYNK_WRITE)
            .appendField(new Blockly.FieldDropdown([
                ["V0","V0"],
                ["V1","V1"],
                ["V2","V2"],
                ["V3","V3"],
                ["V4","V4"],
                ["V5","V5"],
                ["V6","V6"],
                ["V7","V7"],
                ["V8","V8"],
                ["V9","V9"],
                ["V10","V10"],
                ["V11","V11"]
                ]),"PIN")
            .appendField(Blockly.Msg.BLYNK_WRITE1)
        this.appendStatementInput("STATEMENT");
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

Blockly.Blocks['blynk_write_getData'] = {
    init: function() {
        this.appendDummyInput("SELECT")
            .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
            .appendField(new Blockly.FieldDropdown([
                ["Button","Button"],
                ["Slider","Slider"],
                // ["Joystick","Joystick"],
                // ["zeRGBa","zeRGBa"],
                ["Step","Step"],
                ["Light(sensor)","Light"],                
            ]),"MOD")
            // .appendField(Blockly.Msg.BLYNK_GET_DATANAME1)
            .appendField(Blockly.Msg.BLYNK_GET_OF)
        this.setInputsInline(true)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setOutput(true,"Number");
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var numString = '1';
        return Blockly.Types.identifyNumber(numString);
    },
    // onchange:function() {
    //     var mod = this.getFieldValue("MOD");
    //     if (mod == "zeRGBa") {
    //         if (this.getInput("INDEX2")) this.removeInput("INDEX2")
    //         if (this.getInput("INDEX3")) this.removeInput("INDEX3")
    //         if (!this.getInput("INDEX1")) {
    //             this.appendDummyInput("INDEX1")
    //                 .appendField(Blockly.Msg.BLYNK_GET_OF1)
    //                 .appendField(new Blockly.FieldDropdown([
    //                     ["R", "0"],
    //                     ["G", "1"],
    //                     ["B", "2"]
    //                 ]),"SELINDEX")
    //                 .appendField(Blockly.Msg.BLYNK_GET_OF2)
    //         }
    //     } else if (mod == "Joystick") {
    //         if (this.getInput("INDEX1")) this.removeInput("INDEX1")
    //         if (this.getInput("INDEX3")) this.removeInput("INDEX3")
    //         if (!this.getInput("INDEX2")) {
    //             this.appendDummyInput("INDEX2")
    //                 .appendField(Blockly.Msg.BLYNK_GET_OF1)
    //                 .appendField(new Blockly.FieldDropdown([
    //                     ["X", "0"],
    //                     ["Y", "1"]
    //                 ]),"SELINDEX")
    //                 .appendField(Blockly.Msg.BLYNK_GET_OF2)
    //         }
    //     } else {
    //         if (this.getInput("INDEX1")) this.removeInput("INDEX1");
    //         if (this.getInput("INDEX2")) this.removeInput("INDEX2")  
    //         if (!this.getInput("INDEX3")) {          
    //             this.appendDummyInput("INDEX3")
    //                 .appendField(Blockly.Msg.BLYNK_GET_OF)
    //         }
    //     }
    // }
};

Blockly.Blocks['blynk_write_getData_joystick'] = {
    init: function() {
        this.appendDummyInput("SELECT")
            .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
            .appendField(new Blockly.FieldDropdown([
                ["Joystick","Joystick"],              
            ]),"MOD")
        this.appendDummyInput("INDEX2")
            .appendField(Blockly.Msg.BLYNK_GET_OF1)
            .appendField(new Blockly.FieldDropdown([
                ["X", "0"],
                ["Y", "1"]
            ]),"SELINDEX")
            .appendField(Blockly.Msg.BLYNK_GET_OF2)
            // .appendField(Blockly.Msg.BLYNK_GET_DATANAME1)
        this.setInputsInline(true)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setOutput(true,"Number");
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var numString = '1';
        return Blockly.Types.identifyNumber(numString);
    },
};

Blockly.Blocks['blynk_write_getData_zeRGBa'] = {
    init: function() {
        this.appendDummyInput("SELECT")
            .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
            .appendField(new Blockly.FieldDropdown([
                ["zeRGBa","zeRGBa"],             
            ]),"MOD")
        this.appendDummyInput("INDEX1")
            .appendField(Blockly.Msg.BLYNK_GET_OF1)
            .appendField(new Blockly.FieldDropdown([
                ["R", "0"],
                ["G", "1"],
                ["B", "2"]
            ]),"SELINDEX")
            .appendField(Blockly.Msg.BLYNK_GET_OF2)
            // .appendField(Blockly.Msg.BLYNK_GET_DATANAME1)
        this.setInputsInline(true)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setOutput(true,"Number");
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var numString = '1';
        return Blockly.Types.identifyNumber(numString);
    },
};

Blockly.Blocks['blynk_write_getData_GraOrAcc'] = {
    init: function() {
        this.appendDummyInput("SELECT")
            .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
            .appendField(new Blockly.FieldDropdown([
                ["Gravity(sensor)","Gravity"],
                ["Accelerometer(sensor)","Accelerometer"],
            ]),"MOD")
        this.appendDummyInput("INDEX1")
            .appendField(Blockly.Msg.BLYNK_GET_OF1)
            .appendField(new Blockly.FieldDropdown([
                ["X", "0"],
                ["Y", "1"],
                ["Z", "2"]
            ]),"SELINDEX")
            .appendField(Blockly.Msg.BLYNK_GET_OF2)
            // .appendField(Blockly.Msg.BLYNK_GET_DATANAME1)
        this.setInputsInline(true)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setOutput(true,"Number");
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var numString = '1.000';
        return Blockly.Types.identifyNumber(numString);
    },
};

Blockly.Blocks['blynk_write_getData_GPS'] = {
    init: function() {
        this.appendDummyInput("SELECT")
            .appendField(Blockly.Msg.BLYNK_GET_DATANAME)
            .appendField(new Blockly.FieldDropdown([
                ["GPS(sensor)","GPS"],
            ]),"MOD")
        this.appendDummyInput("INDEX1")
            .appendField(Blockly.Msg.BLYNK_GET_OF1)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.BLYNK_GPS_LATITUDE, "0"],
                [Blockly.Msg.BLYNK_GPS_LONGITUDE, "1"],
                [Blockly.Msg.BLYNK_GPS_ALTITUDE, "2"],
                [Blockly.Msg.BLYNK_GPS_SPEED, "3"],
            ]),"SELINDEX")
            .appendField(Blockly.Msg.BLYNK_GET_OF2)
            // .appendField(Blockly.Msg.BLYNK_GET_DATANAME1)
        this.setInputsInline(true)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setOutput(true,"Number");
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var numString = '1.000';
        return Blockly.Types.identifyNumber(numString);
    },
};

/**
 *
 */
Blockly.Blocks['blynk_read'] = {
    /**
     * Block for creating a digtial pin selector.
     * @this Blockly.Block
     */
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("./../blockly/media/blynk_header_up.png", 150, 60, "15"));
        this.appendDummyInput()
            .appendField(" "+ Blockly.Msg.BLYNK_SELECT)
            .appendField(new Blockly.FieldDropdown([
                ["Value Display","VD"],
                ["Label Dispaly","LD"],
                ["Gauge","GA"],
                ["Level","LE"],
            ]),"SELECT")
        this.appendDummyInput()
            .appendField(" "+Blockly.Msg.BLYNK_READ)
            .appendField(new Blockly.FieldDropdown([
                ["V0","V0"],
                ["V1","V1"],
                ["V2","V2"],
                ["V3","V3"],
                ["V4","V4"],
                ["V5","V5"],
                ["V6","V6"],
                ["V7","V7"],
                ["V8","V8"],
                ["V9","V9"],
                ["V10","V10"],
                ["V11","V11"]
                ]),"PIN")
            .appendField(Blockly.Msg.BLYNK_READ1)                  
        this.appendValueInput("ADD0")
            .appendField(Blockly.Msg.BLYNK_DATA+"01")
            .setAlign(Blockly.ALIGN_RIGHT)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['blynk_create_with_item']));
        this.setTooltip("");
        this.setHelpUrl("");
    },
    mutationToDom: function() {
        var container = document.createElement('mutation'); 
        container.setAttribute('items', this.itemCount_);
        return container;
    },
    /**
     * Parse XML to restore the inputs.
     * @param {!Element} xmlElement XML storage element.
     * @this Blockly.Block
     */
    domToMutation: function(xmlElement) {
        this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
        this.updateShape_();
    },
    /**
     * Populate the mutator's dialog with this block's components.
     * @param {!Blockly.Workspace} workspace Mutator's workspace.
     * @return {!Blockly.Block} Root block in mutator.
     * @this Blockly.Block
     */
    decompose: function(workspace) {
        var containerBlock = workspace.newBlock('blynk_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('blynk_create_with_item');
            itemBlock.initSvg();
            connection.connect(itemBlock.previousConnection);
            connection = itemBlock.nextConnection;
        }
        return containerBlock;
    },
    /**
     * Reconfigure this block based on the mutator dialog's components.
     * @param {!Blockly.Block} containerBlock Root block in mutator.
     * @this Blockly.Block
     */
    compose: function(containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        // Count number of inputs.
        var connections = [];
        while (itemBlock) {
            connections.push(itemBlock.valueConnection_);
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
        // Disconnect any children that don't belong.
        for (var i = 0; i < this.itemCount_; i++) {
            var connection = this.getInput('ADD' + i).connection.targetConnection;
            if (connection && connections.indexOf(connection) == -1) {
                connection.disconnect();
            }
        }
        this.itemCount_ = connections.length;
        this.updateShape_();
        // Reconnect any child blocks.
        for (var i = 0; i < this.itemCount_; i++) {
            Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
        }
    },
    /**
     * Store pointers to any connected child blocks.
     * @param {!Blockly.Block} containerBlock Root block in mutator.
     * @this Blockly.Block
     */
    saveConnections: function(containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        var i = 0;
        while (itemBlock) {
            var input = this.getInput('ADD' + i);
            itemBlock.valueConnection_ = input && input.connection.targetConnection;
            i++;
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
    },
    /**
     * Modify this block to have the correct number of inputs.
     * @private
     * @this Blockly.Block
     */
    updateShape_: function() {
        // Add new inputs.
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i)
                    .appendField(Blockly.Msg.BLYNK_DATA+"0"+(i+1))
                    .setAlign(Blockly.ALIGN_RIGHT)
            }
        }
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};
Blockly.Blocks['blynk_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.blynk.hue);
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};
Blockly.Blocks['blynk_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.blynk.hue);
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};



Blockly.Blocks['blynk_virtualWrite'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_VIRTUALWRITE)
            .appendField(new Blockly.FieldDropdown([
                ["V1","V1"],
                ["V2","V2"],
                ["V3","V3"],
                ["V4","V4"],
                ["V5","V5"],
                ["V6","V6"],
                ["V7","V7"],
                ["V8","V8"],
                ["V9","V9"],
                ["V10","V10"],
                ["V11","V11"],
                ]),"PIN")
        this.appendValueInput("ADD0")
            .appendField(Blockly.Msg.BLYNK_DATA+"01")
            .setAlign(Blockly.ALIGN_RIGHT)
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['blynk_create_with_item']));
        this.setTooltip("");
        this.setHelpUrl("");
    },
    mutationToDom: function() {
        var container = document.createElement('mutation'); 
        container.setAttribute('items', this.itemCount_);
        return container;
    },
    /**
     * Parse XML to restore the inputs.
     * @param {!Element} xmlElement XML storage element.
     * @this Blockly.Block
     */
    domToMutation: function(xmlElement) {
        this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
        this.updateShape_();
    },
    /**
     * Populate the mutator's dialog with this block's components.
     * @param {!Blockly.Workspace} workspace Mutator's workspace.
     * @return {!Blockly.Block} Root block in mutator.
     * @this Blockly.Block
     */
    decompose: function(workspace) {
        var containerBlock = workspace.newBlock('blynk_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('blynk_create_with_item');
            itemBlock.initSvg();
            connection.connect(itemBlock.previousConnection);
            connection = itemBlock.nextConnection;
        }
        return containerBlock;
    },
    /**
     * Reconfigure this block based on the mutator dialog's components.
     * @param {!Blockly.Block} containerBlock Root block in mutator.
     * @this Blockly.Block
     */
    compose: function(containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        // Count number of inputs.
        var connections = [];
        while (itemBlock) {
            connections.push(itemBlock.valueConnection_);
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
        // Disconnect any children that don't belong.
        for (var i = 0; i < this.itemCount_; i++) {
            var connection = this.getInput('ADD' + i).connection.targetConnection;
            if (connection && connections.indexOf(connection) == -1) {
                connection.disconnect();
            }
        }
        this.itemCount_ = connections.length;
        this.updateShape_();
        // Reconnect any child blocks.
        for (var i = 0; i < this.itemCount_; i++) {
            Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);
        }
    },
    /**
     * Store pointers to any connected child blocks.
     * @param {!Blockly.Block} containerBlock Root block in mutator.
     * @this Blockly.Block
     */
    saveConnections: function(containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        var i = 0;
        while (itemBlock) {
            var input = this.getInput('ADD' + i);
            itemBlock.valueConnection_ = input && input.connection.targetConnection;
            i++;
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
    },
    /**
     * Modify this block to have the correct number of inputs.
     * @private
     * @this Blockly.Block
     */
    updateShape_: function() {
        // Add new inputs.
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i)
                    .appendField(Blockly.Msg.BLYNK_DATA+"0"+(i+1))
                    .setAlign(Blockly.ALIGN_RIGHT)
            }
        }
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};


Blockly.Blocks['blynk_timer'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("./../blockly/media/blynk_time.png", 150, 60, "15"));
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_TIME_SETTING)
            .appendField(new Blockly.FieldDropdown([
                ["1","1000"],
                ["2","2000"],
                ["3","3000"],
                ["4","4000"],
                ["5","5000"],
                ["6","6000"],
                ["7","7000"],
                ["8","8000"],
                ["9","9000"],
                ["10","10000"],
                ["15","11000"],
                ["30","30000"],
                ]),"TIME")
                .appendField(Blockly.Msg.BLYNK_TIME_SECOND)
        this.appendStatementInput("DO")
            .appendField(Blockly.Msg.BLYNK_TIME_DO)
        this.setColour(Blockly.Blocks.blynk.hue);
        // this.setPreviousStatement(true);
        // this.setNextStatement(true);
        this.setTooltip("");
        this.setHelpUrl("");
    }
}


//not used now
Blockly.Blocks['blynk_connect'] = {
    /**
     * Block for creating a digtial pin selector.
     * @this Blockly.Block
     */
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("./../blockly/media/blynk_header.png", 150, 60, "15"));
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_CONNECT);
        this.appendStatementInput("STATEMENT");
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setTooltip("");
        this.setHelpUrl("");
    },

};

//not used now
Blockly.Blocks['blynk_log'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.BLYNK_LOG)
        this.appendValueInput("CONTENT")
            .setCheck(null);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setInputsInline(true);
        this.setColour(Blockly.Blocks.blynk.hue);
        this.setTooltip('');
        this.setHelpUrl('');
    }
};
