'use strict';

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

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

Blockly.Blocks.wifiserver.HUE = "#293278";

/**wifi server
 *setup for server,set port

 */
Blockly.Blocks['wifiServer_setup'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage(
                // "http://cocorobo.cn/cocoblockly/blockly/media/wifi_server.png", 40, 40, "15"))
                "./../blockly/media/wifi_server.png", 40, 40, "15"))
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SETUP)
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/**wifi server
 *set server Root webpage 
 *@param {blocks} statement: for webpage block
 */
Blockly.Blocks['wifiServer_setRootPage'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SETROUTER)
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SETROOTPAGE)
        this.appendStatementInput("STATEMENT0")
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/**wifi server
 *set server url with response when HTTP requests
 *@param {String} url: String for Router path
 *@param {blocks} statement: motion for Router path
 */
Blockly.Blocks['wifiServer_setRouter'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SETROUTER)
        this.appendDummyInput("ADD0")
            .appendField(Blockly.Msg.WIFISERVER_SETROUTER_SET)
            .appendField(new Blockly.FieldTextInput("/"), "URL0")
        this.appendStatementInput("STATEMENT0")
            .appendField(Blockly.Msg.WIFISERVER_SETROUTER_WITH)
        this.itemCount_ = 1;
        this.setMutator(new Blockly.Mutator(['ServerRouter_create_with_item']));
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setPreviousStatement(true);
        this.setNextStatement(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('ServerRouter_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('ServerRouter_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');
        // var itemBlock = containerBlock.nextConnection.targetBlock();
        // 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);
            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)) {
                this.appendDummyInput("ADD" + i)
                    .appendField(Blockly.Msg.WIFISERVER_SETROUTER_SET)
                    .appendField(new Blockly.FieldTextInput("/"), "URL" + i)
                this.appendStatementInput("STATEMENT" + i)
                    .appendField(Blockly.Msg.WIFISERVER_SETROUTER_WITH)
            }
        }
        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            this.removeInput('STATEMENT' + i);
            i++;
        }
    }
};
Blockly.Blocks['ServerRouter_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setTooltip('');
        this.contextMenu = false;
    }
};
Blockly.Blocks['ServerRouter_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};

/**WiFi Server
 *send JSON data from Server
 *@param {variable} txdata the data name
 *@param {String/int} data a collection of data as JSON 
 */
Blockly.Blocks['wifiServer_Send'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SEND)
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_LIST)
            .appendField(new Blockly.FieldTextInput("Data_send"), "VAR");
        this.appendValueInput("ADD0")
            .appendField("Data0")
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.Mutator(['ServerSend_create_with_item']));
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        // 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('ServerSend_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('ServerSend_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);
                input.appendField("Data" + i);
            }
        }
        // Remove deleted inputs.
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    }
};
Blockly.Blocks['ServerSend_create_with_container'] = {
    /**
     * Mutator block for list container.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_CONTAINER_TITLE_ADD);
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};
Blockly.Blocks['ServerSend_create_with_item'] = {
    /**
     * Mutator bolck for adding items.
     * @this Blockly.Block
     */
    init: function() {
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.THINGSPEAK_CREATE_WITH_ITEM_TITLE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};

/**WiFi Server
 * receive JSON data from Client,and parse it into List
 * @param {variable} var the list name of JSON data parse into
 * @param {}
 */
Blockly.Blocks['wifiServer_Receive'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_RECEIVE)
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_RECEIVE_TO)
            .appendField(new Blockly.FieldTextInput("Data_receive"), "VAR")
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_RECEIVE_LENGTH)
            .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"],
            ]), "LENGTH")
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/**WiFi Server
 * receive JSON data from Client,and parse it into List
 * @param {variable} var the list name of JSON data parse into
 * @param {}
 */
Blockly.Blocks['wifiServer_Receive_getValue'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(" " + Blockly.Msg.WIFISERVER_RECEIVE_GET)
            .appendField(new Blockly.FieldTextInput("Data_receive"), "VAR")
            .appendField(" " + Blockly.Msg.WIFISERVER_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.WIFISERVER_RECEIVE_GET_LINE3)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.WIFISERVER_RECEIVE_GET_INT, "Int"],
                [Blockly.Msg.WIFISERVER_RECEIVE_GET_STRING, "String"]
            ]), "TYPE")
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        this.setOutput(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
    getBlockType: function() {
        var type = this.getFieldValue("TYPE");
        switch (type) {
            case "Int":
                return Blockly.Types.NUMBER;
                break;
            case "String":
                return Blockly.Types.TEXT;
                break;
        }
        return Blockly.Types.UNDEF;
    }
}

/*wifi server 
 *if there is no url, set server with response when HTTP requests
 */
Blockly.Blocks['wifiServer_onNotFound'] = {
    init: function() {
        this.appendValueInput("VAR")
            .appendField(Blockly.Msg.WIFISERVER_SETROUTER_ONNOTFOUND);
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        // this.setOutput(true,Blockly.Types.TEXT.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/*wifi server 
 *server send to client
 */
Blockly.Blocks['wifiServer_serverSend'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_SERVERSEND);
        this.appendValueInput("CODE")
            .appendField(Blockly.Msg.WIFISERVER_SERVERSEND_CODE);
        this.appendValueInput("TYPE")
            .appendField(Blockly.Msg.WIFISERVER_SERVERSEND_TYPE);
        this.appendValueInput("CONTENT")
            .appendField(Blockly.Msg.WIFISERVER_SERVERSEND_CONTENT);
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        // this.setOutput(true,Blockly.Types.TEXT.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/*wifi server 
 *function handleClient() to wait for client connection
 *and handle clients' HTTP request
 */
Blockly.Blocks['wifiServer_handleClient'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_HANDLECLIENT)
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        // this.setOutput(true,Blockly.Types.TEXT.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};

/*wifi server 
 *wait for client connection
 */
Blockly.Blocks['wifiServer_waitConnection'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.WIFISERVER_WAIT_CONNECTION)
        this.setColour(Blockly.Blocks.wifiserver.HUE);
        // this.setOutput(true,Blockly.Types.TEXT.output);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        // this.setInputsInline(true);
        this.setTooltip("");
        this.setHelpUrl("");
    },
};