'use strict';

goog.provide('Blockly.Blocks.wificomms');

goog.require('Blockly.Blocks');
goog.require('Blockly.Types');

Blockly.Blocks.wificomms.HUE = "#db3e37";

Blockly.Blocks['wificomms_setup'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/cocomod_blockly_wifi.png", 140, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/wifi-data_transfer.png", 50, 40, "0"));
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFI_SETUP);
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/*send message from  main_comtrol to wifi */
Blockly.Blocks['wificomms_sendMsg'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFI_SENDMSG)
            .appendField(new Blockly.FieldVariable("dataOut"), "dataVar");
        this.setColour(Blockly.Blocks.wificomms.HUE);
        // this.setOutput(true,Blockly.Types.BOOLEAN.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getVarType: function(varName) {
        return Blockly.Types.ARRAY;
    }
};

/*receive message from main_comtrol to wifi */
Blockly.Blocks['wificomms_receiveMsg'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFI_RECEIVEMSG)
            .appendField(new Blockly.FieldVariable("dataIn"), "dataVar");
        this.setColour(Blockly.Blocks.wificomms.HUE);
        // this.setOutput(true,Blockly.Types.BOOLEAN.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getVarType: function(varName) {
        return Blockly.Types.ARRAY;
    }
};

/*check if sucessfully receive message from main_comtrol to wifi */
Blockly.Blocks['wificomms_receiveMsg_isSuccessed'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFI_RECEIVEMSG_ISSUCCESS);
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.setOutput(true, Blockly.Types.BOOLEAN.output);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};





/*************************
 *       version 2       *
 *       eaysmode        *
 *************************/

/*wifi easymode
 * wifi-2-main transfer
 * send msg from wifi to main
 */
Blockly.Blocks['wifiTransfer_send_old'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/cocomod_blockly_wifi.png", 140, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/transfer-2.png", 50, 40, "0"));
        // this.appendDummyInput()
        //     .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND)
        //     .appendField(new Blockly.FieldDropdown([
        //         ["txData", "txData"]
        //     ]), "DATAMAIN");
        this.appendDummyInput()
            .appendField("old "+Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND_LINE2);
        this.appendValueInput("ADD0")
            .appendField(Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND_VALUE + "0")
        this.setColour(220);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");

        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['Transfer_create_with_item']));


    },
    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('Transfer_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('Transfer_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() {
        // if (this.itemCount_ && this.getInput('EMPTY')) {
        //     this.removeInput('EMPTY');
        // } else if (!this.itemCount_ && !this.getInput('EMPTY')) {
        //     this.appendDummyInput('EMPTY')
        //         .appendField(this.newQuote_(true))
        //         .appendField(this.newQuote_(false));
        // }

        var i = 1;
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
        // 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.WIFIEASYMODE_TRANSFER_SEND_VALUE + i);
            }

        }
        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};

Blockly.Blocks['Transfer_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};

Blockly.Blocks['Transfer_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};

/*wifi easymode
 * wifi-2-main transfer
 * receive msg from main to wifi
 */
Blockly.Blocks['wifiTransfer_receive_old'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/cocomod_blockly_wifi.png", 140, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/transfer-2.png", 50, 40, "0"));
        this.appendDummyInput()
            .appendField("old "+ Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE)
        // this.appendDummyInput()
        //     .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_LINE2)
        //     .appendField(new Blockly.FieldDropdown([
        //         ["rxData", "rxData"]
        //     ]), "DATAMAIN");
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_LINE3)
            .appendField(new Blockly.FieldDropdown([
                ["1", "1"],
                ["2", "2"],
                ["3", "3"],
                ["4", "4"],
                ["5", "5"],
                ["6", "6"],
                ["7", "7"],
                ["8", "8"],
                ["9", "9"],
                ["10", "10"],
                ["11", "11"],
                ["12", "12"],
            ]), "LENGTH");
        this.setColour(220);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getVarType: function(varName) {
        let vartype = Blockly.Types.ARRAY;
        return vartype;
    }
}

/*wifi easymode
 * wifi-2-main transfer
 * get data from dataMain 
 * @param {dataMain} :where data tranferred stored in 
 */
Blockly.Blocks['wifiTransfer_receive_getValue_old'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET)
            // .appendField(new Blockly.FieldDropdown([
            //     ["rxData", "rxData"]
            // ]), "DATAMAIN")
            .appendField("old "+ Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE2)
            .appendField(new Blockly.FieldDropdown([
                ["0", "0"],
                ["1", "1"],
                ["2", "2"],
                ["3", "3"],
                ["4", "4"],
                ["5", "5"],
                ["6", "6"],
                ["7", "7"],
                ["8", "8"],
                ["9", "9"],
                ["10", "10"],
                ["11", "11"],
            ]), "INDEX")
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE3)
            // .appendField(new Blockly.FieldDropdown([
            //     ["String", ""],
            //     ["Number", ".toInt()"],
            //     ["Float", ".toFloat()"],
            // ]), "TYPE")
            // .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE4)
        this.setColour(220);
        this.setOutput(true)
            // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var type = this.getFieldValue("TYPE");
        switch (type) {
            case "" :
                return Blockly.Types.TEXT;
            case ".toInt()":
                return Blockly.Types.NUMBER;
            case ".toFloat()":
                return Blockly.Types.LARGE_NUMBER;
        }
        return Blockly.Types.NUMBER;
    },
    getOutputType: function() {
        var type = this.getFieldValue("TYPE");
        switch (type) {
            case "" :
                return Blockly.Types.TEXT.output
            case ".toInt()":
                return Blockly.Types.NUMBER.output;
            case ".toFloat()":
                return Blockly.Types.LARGE_NUMBER.output;
        }
        return Blockly.Types.NUMBER.output;
    }

}

/*************************
 *       version 3       *
 *       eaysmode        *
 *************************/

/*wifi easymode
 * wifi-2-main transfer
 * send msg from wifi to main
 */
Blockly.Blocks['wifiTransfer_send'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/cocomod_blockly_wifi.png", 140, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/transfer-2.png", 50, 40, "0"));
        // this.appendDummyInput()
        //     .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND)
        //     .appendField(new Blockly.FieldDropdown([
        //         ["txData", "txData"]
        //     ]), "DATAMAIN");
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND_LINE2);
        this.appendValueInput("ADD0")
            .appendField(Blockly.Msg.WIFIEASYMODE_TRANSFER_SEND_VALUE + "0")
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");

        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['Transfer_create_with_item']));


    },
    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('Transfer_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('Transfer_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() {
        // if (this.itemCount_ && this.getInput('EMPTY')) {
        //     this.removeInput('EMPTY');
        // } else if (!this.itemCount_ && !this.getInput('EMPTY')) {
        //     this.appendDummyInput('EMPTY')
        //         .appendField(this.newQuote_(true))
        //         .appendField(this.newQuote_(false));
        // }

        var i = 1;
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
        // 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.WIFIEASYMODE_TRANSFER_SEND_VALUE + i);
            }

        }
        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};

Blockly.Blocks['Transfer_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};

Blockly.Blocks['Transfer_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};

/*wifi easymode
 * wifi-2-main transfer
 * receive msg from main to wifi
 */
Blockly.Blocks['wifiTransfer_receive'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/cocomod_blockly_wifi.png", 140, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/transfer-2.png", 50, 40, "0"));
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE)
        // this.appendDummyInput()
        //     .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_LINE2)
        //     .appendField(new Blockly.FieldDropdown([
        //         ["rxData", "rxData"]
        //     ]), "DATAMAIN");
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_LINE3)
            .appendField(new Blockly.FieldDropdown([
                ["1", "1"],
                ["2", "2"],
                ["3", "3"],
                ["4", "4"],
                ["5", "5"],
                ["6", "6"],
                ["7", "7"],
                ["8", "8"],
                ["9", "9"],
                ["10", "10"],
                ["11", "11"],
                ["12", "12"],
            ]), "LENGTH");
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getVarType: function(varName) {
        let vartype = Blockly.Types.ARRAY;
        return vartype;
    }
}

/*wifi easymode
 * wifi-2-main transfer
 * get data from dataMain 
 * @param {dataMain} :where data tranferred stored in 
 */
Blockly.Blocks['wifiTransfer_receive_getValue'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET)
            // .appendField(new Blockly.FieldDropdown([
            //     ["rxData", "rxData"]
            // ]), "DATAMAIN")
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE2)
            .appendField(new Blockly.FieldDropdown([
                ["0", "0"],
                ["1", "1"],
                ["2", "2"],
                ["3", "3"],
                ["4", "4"],
                ["5", "5"],
                ["6", "6"],
                ["7", "7"],
                ["8", "8"],
                ["9", "9"],
                ["10", "10"],
                ["11", "11"],
            ]), "INDEX")
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE3)
            .appendField(new Blockly.FieldDropdown([
                ["String", ""],
                ["Number", ".toInt()"],
                ["Float", ".toFloat()"],
            ]), "TYPE")
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_TRANSFER_RECEIVE_GET_LINE4)
        this.setColour(Blockly.Blocks.wificomms.HUE);
        this.setOutput(true)
            // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var type = this.getFieldValue("TYPE");
        switch (type) {
            case "" :
                return Blockly.Types.TEXT;
            case ".toInt()":
                return Blockly.Types.NUMBER;
            case ".toFloat()":
                return Blockly.Types.LARGE_NUMBER;
        }
        return Blockly.Types.NUMBER;
    },
    getOutputType: function() {
        var type = this.getFieldValue("TYPE");
        switch (type) {
            case "" :
                return Blockly.Types.TEXT.output
            case ".toInt()":
                return Blockly.Types.NUMBER.output;
            case ".toFloat()":
                return Blockly.Types.LARGE_NUMBER.output;
        }
        return Blockly.Types.NUMBER.output;
    }

}