'use strict';

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

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

Blockly.Blocks.wifiwebservices.HUE = "#37a0ce";

/*IFTTT service
 *method to post http request with Json
 *Json with three data
 */
Blockly.Blocks['wifiwebservices_ifttt_simple'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT);
        this.appendValueInput("KEY")
            .setCheck("Text")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT_SET_KEY);
        this.appendValueInput("EVENT")
            .setCheck("Text")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT_SET_EVENT);
        this.appendValueInput("VALUE1")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT_SET_VALUE1);
        this.appendValueInput("VALUE2")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT_SET_VALUE2);
        this.appendValueInput("VALUE3")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_IFTTT_SET_VALUE3);
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/*Thinkspeak service
 *method to get http request with data in url
 *field1, field2, field3
 */
Blockly.Blocks['wifiwebservices_thinkspeak_simple'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFIWEBSERVICES_THINKSPEAK);
        this.appendValueInput("KEY")
            .setCheck("Text")
            .appendField(Blockly.Msg.WIFIWEBSERVICES_THINKSPEAK_SET_KEY);
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['thingspeak_create_with_item']));
        // this.appendValueInput("FIELD")
        // .appendField(Blockly.Msg.WIFIWEBSERVICES_THINKSPEAK_SET_FIELD1);
        // this.appendValueInput("VALUE")
        // .appendField(Blockly.Msg.WIFIWEBSERVICES_THINKSPEAK_SET_VALUE);
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        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('thingspeak_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('thingspeak_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));
        // }
        // Add new inputs.
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i);
                input.appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_INPUT_WITH)
                    .appendField(new Blockly.FieldTextInput("field" + (i + 1)), 'FIELD' + i)

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

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

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



/** 
 *CocoCloud Service 
 *method POST a http request with a JSON data
 *@param url :http://staging.cocorobo.cn/cloud/iot/{events}
 *@param event get from URL://cocorobo.cn/cloud/iot/data/apikey/{@param APIKEY}/event
 *@param data JSON form - generate from clouddata blocks
 */
Blockly.Blocks['wifiwebservices_cococloud_simple_post'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.COCOCLOUD_TITLE);
        this.appendValueInput('ADD0')
            .appendField(Blockly.Msg.COCOCLOUD_POST)
            .appendField(new Blockly.FieldDropdown([
                ["event", "event"]
            ]), "event0");
        this.itemCount = 1;
        this.updateShape_();
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    /**
     * Modify this block to have the correct number of inputs.
     * @private
     * @this Blockly.Block
     */
    updateShape_: function() {
        // Add new inputs.
        var self = this;
        var input = this.getInput('ADD0');
        var api_key = document.getElementById('api-key').innerHTML || "";
        $.ajax({
            url: '//api.cocorobo.cn/iot/data/apikey/' + api_key + '/event/',
            // url: '//staging.cocorobo.cn/api/iot/data/apikey/' + api_key + '/event/',
            xhrFields: {
                withCredentials: true
            },
            type: 'GET',
            success: function(data) {
                var eventsName = [];
                if (data != null) {
                    $.each(data, function(i, obj) {
                        var temparray = []
                        temparray.push(obj.name);
                        temparray.push(obj.url);
                        eventsName.push(temparray);
                    });
                    self.eventsName = eventsName;
                    input.removeField("event0");
                    input.appendField(new Blockly.FieldDropdown(eventsName), "event0");
                }
            },
            error: function(error) {
                console.log("error");
            }
        });
    }
};

/** 
 *CocoCloud Service 
 *method GET a http request to get a JSON data
 *@param url :http://staging.cocorobo.cn/cloud/iot/{events}
 *@param event get from URL://cocorobo.cn/cloud/iot/data/apikey/{@param APIKEY}/event
 * data JSON form
 */
Blockly.Blocks['wifiwebservices_cococloud_simple_get'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.COCOCLOUD_TITLE);
        this.appendDummyInput("iuput_id0")
            .appendField(Blockly.Msg.COCOCLOUD_GET, "text_field0")
            .appendField(new Blockly.FieldDropdown([
                ["event", "event"]
            ]), "event0")
            .appendField(Blockly.Msg.COCOCLOUD_GET1, "text_field1");
        this.itemCount = 1;
        this.updateShape_();
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    /**
     * Modify this block to have the correct number of inputs.
     * @private
     * @this Blockly.Block
     */
    updateShape_: function() {
        // Add new inputs.
        var self = this;
        var input = this.getInput('iuput_id0');
        var api_key = document.getElementById('api-key').innerHTML || "";
        $.ajax({
            url: '//api.cocorobo.cn/iot/data/apikey/' + api_key + '/event/',
            // url: '//staging.cocorobo.cn/api/iot/data/apikey/' + api_key + '/event/',
            xhrFields: {
                withCredentials: true
            },
            type: 'GET',
            success: function(data) {
                var eventsName = [];
                if (data != null) {
                    $.each(data, function(i, obj) {
                        var temparray = [];
                        temparray.push(obj.name);
                        temparray.push(obj.url);
                        eventsName.push(temparray);
                    });
                    self.eventsName = eventsName;
                    input.removeField("text_field0");
                    input.removeField("event0");
                    input.removeField("text_field1");
                    input.appendField(Blockly.Msg.COCOCLOUD_GET, "text_field0")
                        .appendField(new Blockly.FieldDropdown(eventsName), "event0")
                        .appendField(Blockly.Msg.COCOCLOUD_GET1, "text_field1");
                }
            },
            error: function(error) {
                console.log("error");
            }
        });
    }
};

/** 
 *CocoCloud Service 
 * get JSON data from cococloud-get-block
 */
Blockly.Blocks['wifiwebservices_cococloud_simple_getPayLoad'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.COCOCLOUD_TITLE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.COCOCLOUD_GETPAYLOAD);
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setOutput(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

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


/*wifi easymode 
 * IFTTT
 * post data {JSON} to Cloud event
 */
Blockly.Blocks['wifiServices_IFTTT'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/blockly-easymode_thingspeak.png", 180, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/blockly-easymode_ifttt.png", 180, 40, "0"));
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_KEY);
        this.appendDummyInput()
            .appendField(" ")
            .appendField(new Blockly.FieldTextInput("bAssF9YJ_7oZP1k4et_IUx"), "IFTTT_KEY")
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_EVENT);
        this.appendDummyInput()
            .appendField(" ")
            .appendField(new Blockly.FieldTextInput("cocorobo_webhook"), "IFTTT_EVENT")
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_TYPE)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.WIFIEASYMODE_IFTTT_POST, "Action"],
                [Blockly.Msg.WIFIEASYMODE_IFTTT_FETCH, "Trigger"]
            ]), "TYPE");

        for (let n = 0; n < 3; n++) {
            if (!this.getInput("data" + n))
                this.appendValueInput("data" + n)
                .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_SENDDATA + n);
        }
        // this.appendValueInput("dataA")
        //     .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_SENDDATA);
        this.onChange();
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getType: function() {
        switch (this.getFieldValue("TYPE")) {
            case "Action":
                return 1;
            case "Trigger":
                return 2;
            default:
                return 0;
        }
    },
    onChange: function() {
        if (this.getType() == 1) {
            for (let n = 0; n < 3; n++) {
                if (!this.getInput("data" + n))
                    this.appendValueInput("data" + n)
                    .appendField(" " + Blockly.Msg.WIFIEASYMODE_IFTTT_SENDDATA + n);
            }
        } else if (this.getType() == 2) {
            var i = 0;
            var substructure
            while (this.getInput('data' + i)) {
                substructure = this.getInputTargetBlock("data" + i);
                if (substructure) {
                    substructure.dispose(true, true);
                }
                this.removeInput('data' + i);
                i++;
            }


        }
    }
}


/*wifi easymode
 *setup for WiFi network
 */
Blockly.Blocks['wifiServices_thingspeak'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/blockly-easymode_thingspeak.png", 180, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/blockly-easymode_thingspeak.png", 180, 40, "0"));
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_THINGSPEAK_APIKEY)
        this.appendDummyInput()
            .appendField(" ")
            .appendField(new Blockly.FieldTextInput("bAssF9YJ_7oZP1k4et_IUx"), "API_KEY")
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_THINGSPEAK_SENDDATA)
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['thingspeakEM_create_with_item']));
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        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('thingspeakEM_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('thingspeakEM_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));
        // }
        // Add new inputs.
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i);
                input.appendField(" " + "Field " + (i + 1) + ":");
            }
        }

        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};
Blockly.Blocks['thingspeakEM_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};
Blockly.Blocks['thingspeakEM_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};



/*wifi easymode
 * CocoCloud 
 * post data {JSON} to Cloud event
 */
Blockly.Blocks['wifiServices_cococloud_post'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/blockly-easymode_thingspeak.png", 180, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/cloud-tx.png", 180, 40, "0"));
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_COCOClOUD_EVENT);
        this.appendDummyInput()
            .appendField(" ")
            // .appendField(new Blockly.FieldDropdown([
            //     ["Your event", "Your event"]
            // ]), "event0");
            .appendField(new Blockly.FieldTextInput("d0f98bb70ae070cd89725780e67dfe6b"), "event0")
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_COCOCLOUD_SENDDATA);
        this.appendValueInput("ADD0")
            // .appendField(Blockly.Msg.WIFIEASYMODE_COCOClOUD_DATA_NAME)
            .appendField(" ")
            .appendField(new Blockly.FieldTextInput("EM_data0"), "field0")
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['cococloud_create_with_item']));
        // this.updateEvent_();
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        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('cococloud_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('cococloud_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));
        // }
        // Add new inputs.
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i);
                input.appendField(" ")
                    .appendField(new Blockly.FieldTextInput("EM_data" + i), "field" + i);
            }
        }

        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
    updateEvent_: function() {
        // Add new inputs.
        var self = this;
        var input = this.getInput('ADD0');
        var api_key = document.getElementById('api-key').innerHTML || "";
        $.ajax({
            url: '//api.cocorobo.cn/iot/data/apikey/' + api_key + '/event/',
            // url: '//staging.cocorobo.cn/api/iot/data/apikey/' + api_key + '/event/',
            xhrFields: {
                withCredentials: true
            },
            type: 'GET',
            success: function(data) {
                var eventsName = [];
                if (data != null) {
                    $.each(data, function(i, obj) {
                        var temparray = []
                        temparray.push(obj.name);
                        temparray.push(obj.url);
                        eventsName.push(temparray);
                    });
                    self.eventsName = eventsName;
                    input.removeField("event0");
                    input.appendField(new Blockly.FieldDropdown(eventsName), "event0");
                }
            },
            error: function(error) {
                console.log("error");
            }
        });
    }
};
Blockly.Blocks['cococloud_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};
Blockly.Blocks['cococloud_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    },

}

/*wifi easymode
 * CocoCloud 
 * post data {JSON} to Cloud event
 */
Blockly.Blocks['wifiServices_cococloud_get'] = {
    init: function() {
        this.appendDummyInput()
            // .appendField(new Blockly.FieldImage("http://cocorobo.cn/cocoblockly/blockly/media/blockly-easymode_thingspeak.png", 180, 40, "0"));
            .appendField(new Blockly.FieldImage("./../blockly/media/cloud-rx.png", 180, 40, "0"));
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_COCOClOUD_EVENT)
        this.appendDummyInput()
            .appendField(" ")
            .appendField(new Blockly.FieldTextInput("d0f98bb70ae070cd89725780e67dfe6b"), "event0")
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFIEASYMODE_COCOCLOUD_GETDATA)
            .appendField(new Blockly.FieldDropdown([
                ["rxCloud", "rxCloud"]
            ]), "VAR")
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

Blockly.Blocks['wifiServices_cococloud_get_data'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_KEY)
            .appendField(new Blockly.FieldDropdown([
                ["rxCloud", "rxCloud"]
            ]), "VAR")
            .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_KEY1)
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_KEY2)
            .appendField(new Blockly.FieldTextInput("EM_data"), "KEY")
            .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_TYPE)
            .appendField(new Blockly.FieldDropdown(
                [
                    ["Text", "Text"],
                    ["Number", "Number"],
                    // ["Boolean", "Boolean"],
                    // ["Large Number", "Large Number"],
                    // ["Decimal", "Decimal"]
                ]), 'VAR_TYPE')
            .appendField(Blockly.Msg.WIFIEASYMODE_COCOCLOUD_END)
            // this.updateEvent_();
        this.setColour(Blockly.Blocks.wifiwebservices.HUE);
        this.setOutput(true);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var blocktype = Blockly.Types.TEXT;
        switch (this.getFieldValue("VAR_TYPE")) {
            case "Text":
                blocktype = Blockly.Types.TEXT;
                break;
            case "Number":
                blocktype = Blockly.Types.NUMBER;
                break;
                // case "Boolean":
                //     blocktype = Blockly.Types.BOOLEAN;
                //     break;
                // case "Large Number":
                //     blocktype = Blockly.Types.LARGE_NUMBER;
                //     break;
                // case "Decimal":
                //     blocktype = Blockly.Types.DECIMAL;
                //     break;
        }
        return blocktype;
    }
};