/* eslint-disable no-unused-expressions */
import * as Blockly from 'blockly';
// import { pythonGenerator } from "blockly/python";
import CategoryColors from './define_color'

// Blockly.Python = pythonGenerator
Blockly.Blocks['custom_text_block'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.numpy_mnist_clear)
            .appendField(new Blockly.FieldTextInput("张三丰"), "TEXT_INPUT");
        // this.setOutput(true, null);
        this.setPreviousStatement(true, null)
        this.setNextStatement(true, null)
        this.setTooltip("");
        this.setHelpUrl("");
        this.setStyle('custom_text_blocks')
    }
};
Blockly.Blocks["CocoRobo_return"] = {
    init: function () {
        this.jsonInit({
            inputsInline: !0,
            nextStatement: null,
            previousStatement: null,
            colour: CategoryColors.Logic,
            tooltip: Blockly.Msg.CocoRobo_RETURN_TOOLTIP,
            message0: Blockly.Msg.CocoRobo_RETURN_MESSAGE0,
            args0: [{
                type: "input_value",
                name: "VAR"
            }]
        })
    }
}
Blockly.Blocks.CocoRobo_try_except = {
    init: function () {
        this.jsonInit({
            message0: "",
            previousStatement: null,
            nextStatement: null,
            colour: CategoryColors.Logic,
            tooltip: Blockly.Msg.CocoRobo_try_except_TOOLTIP,
            helpUrl: ""
        });
        this.appendStatementInput("TRY").appendField("try");
        this.appendStatementInput("EXCEPT").appendField("except");
    }
}

Blockly.Blocks.CocoRobo_try_except_finally = {
    init: function () {
        this.jsonInit({
            message0: "",
            previousStatement: null,
            nextStatement: null,
            colour: CategoryColors.Logic,
            tooltip: Blockly.Msg.CocoRobo_try_except_finally_TOOLTIP,
            helpUrl: ""
        });
        this.appendStatementInput("TRY").appendField("try");
        this.appendStatementInput("EXCEPT").appendField("except");
        this.appendStatementInput("FINALLY").appendField("finally")
    }
};

Blockly.Blocks.CocoRobo_type = {
    init: function () {
        this.jsonInit({
            message0: "值 %1 的类型",
            args0: [{
                type: "input_value",
                name: "VAR"
            }],
            output: null,
            colour: CategoryColors.Logic,
            tooltip: "返回当前值的类型",
            helpUrl: ""
        })
    }
};
Blockly.Blocks.CocoRobo_type_is = {
    init: function () {
        this.jsonInit({
            message0: '值 %1 的类型为 %2',
            args0: [{
                type: "input_value",
                name: "VAR"
            }, {
                name: "TYPE",
                options: [
                    ["int", "int"],
                    ["float", "float"],
                    ["bool", "bool"],
                    ["str", "str"],
                    ["list", "list"],
                    ["tuple", "tuple"],
                    ["set", "set"],
                    ["dict", "dict"],
                    ["bytes", "bytes"],
                    ["bytearray", "bytearray"],
                    ["complex", "complex"]
                ],
                type: "field_dropdown"
            }],
            output: "Boolean",
            colour: CategoryColors.Logic,
            // tooltip: Blockly.Msg.CocoRobo_TYPE_IS_TOOLTIP,
            helpUrl: Blockly.Msg.CocoRobo_TYPE_IS_HELPURL
        });
        var thisBlock = this;
        this.setTooltip(function () {
            return Blockly.Msg.CocoRobo_TYPE_IS_TOOLTIP.replace('%2',
                thisBlock.getFieldValue('TYPE'));
        });
    }
};
Blockly.Blocks.CocoRobo_eval = {
    init: function () {
        this.jsonInit({
            message0: '计算表达式 %1 的结果',
            args0: [{
                check: "String",
                type: "input_value",
                name: "VAR"
            }],
            output: null,
            colour: CategoryColors.Logic,
            tooltip: '计算字符串表达式，并返回结果',
            helpUrl: ""
        })
    }
};

const HUE = "#9d64fd"
Blockly.Blocks.controls_repeat_forever = {
    init: function () {
        this.jsonInit({
            message0: Blockly.Msg.CONTROLS_REPEAT_FOREVER,
            previousStatement: null,
            nextStatement: null,
            colour: HUE,
            tooltip: Blockly.Msg.CONTROLS_REPEAT_FOREVER_TOOLTIP,
            helpUrl: Blockly.Msg.CONTROLS_REPEAT_HELPURL
        });
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO)
    }
};
Blockly.Blocks.controls_repeat_ext = {
    init: function () {
        this.jsonInit({
            message0: Blockly.Msg.CONTROLS_REPEAT_TITLE,
            args0: [{
                type: "input_value",
                name: "TIMES",
                check: "Number"
            }],
            previousStatement: null,
            nextStatement: null,
            colour: HUE,
            tooltip: Blockly.Msg.CONTROLS_REPEAT_TOOLTIP,
            helpUrl: Blockly.Msg.CONTROLS_REPEAT_HELPURL
        });
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO)
    }
};
Blockly.Blocks.controls_repeat = {
    init: function () {
        this.jsonInit({
            message0: Blockly.Msg.CONTROLS_REPEAT_TITLE,
            args0: [{
                type: "field_number",
                name: "TIMES",
                value: 10,
                min: 0,
                precision: 1
            }],
            previousStatement: null,
            nextStatement: null,
            colour: HUE,
            tooltip: Blockly.Msg.CONTROLS_REPEAT_TOOLTIP,
            helpUrl: Blockly.Msg.CONTROLS_REPEAT_HELPURL
        });
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO)
    }
};
Blockly.Blocks.controls_whileUntil = {
    init: function () {
        var a = [[Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE, "WHILE"], [Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL, "UNTIL"]];
        this.setHelpUrl(Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL);
        this.setColour(HUE);
        this.appendValueInput("BOOL").setCheck("Boolean").appendField(new Blockly.FieldDropdown(a), "MODE");
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO);
        this.setPreviousStatement(!0);
        this.setNextStatement(!0);
        var b = this;
        this.setTooltip(function () {
            var a = b.getFieldValue("MODE");
            return {
                WHILE: Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE,
                UNTIL: Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL
            }[a]
        })
    }
};
Blockly.Blocks.controls_for = {
    init: function () {
        this.jsonInit({
            message0: Blockly.Msg.CONTROLS_FOR_TITLE,
            args0: [{
                type: "field_variable",
                name: "VAR",
                variable: null
            }, {
                type: "input_value",
                name: "FROM",
                check: "Number",
                align: "RIGHT"
            }, {
                type: "input_value",
                name: "TO",
                check: "Number",
                align: "RIGHT"
            }, {
                type: "input_value",
                name: "BY",
                check: "Number",
                align: "RIGHT"
            }],
            inputsInline: !0,
            previousStatement: null,
            nextStatement: null,
            colour: HUE,
            helpUrl: Blockly.Msg.CONTROLS_FOR_HELPURL
        });
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_FOR_INPUT_DO);
        var a = this;
        this.setTooltip(function () {
            return Blockly.Msg.CONTROLS_FOR_TOOLTIP.replace("%1", a.getFieldValue("VAR"))
        })
    },
    // customContextMenu: function (a) {
    //     if (!this.isCollapsed()) {
    //         var b = {
    //             enabled: !0
    //         }
    //             , c = this.getFieldValue("VAR");
    //         b.text = Blockly.Msg.VARIABLES_SET_CREATE_GET.replace("%1", c);
    //         c = goog.dom.createDom("field", null, c);
    //         c.setAttribute("name", "VAR");
    //         c = goog.dom.createDom("block", null, c);
    //         c.setAttribute("type", "variables_get");
    //         b.callback = Blockly.ContextMenu.callbackFactory(this, c);
    //         a.push(b)
    //     }
    // }
};
Blockly.Blocks.controls_forEach = {
    init: function () {
        this.jsonInit({
            message0: Blockly.Msg.CONTROLS_FOREACH_TITLE,
            args0: [{
                type: "field_variable",
                name: "VAR",
                variable: null
            }, {
                type: "input_value",
                name: "LIST",
                check: "Array"
            }],
            previousStatement: null,
            nextStatement: null,
            colour: HUE,
            helpUrl: Blockly.Msg.CONTROLS_FOREACH_HELPURL
        });
        this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_FOREACH_INPUT_DO);
        var a = this;
        this.setTooltip(function () {
            return Blockly.Msg.CONTROLS_FOREACH_TOOLTIP.replace("%1", a.getFieldValue("VAR"))
        })
    },
    customContextMenu: Blockly.Blocks.controls_for.customContextMenu
};
Blockly.Blocks.controls_flow_statements = {
    init: function () {
        var a = [[Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK, "BREAK"], [Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE, "CONTINUE"]];
        this.setHelpUrl(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL);
        this.setColour(HUE);
        this.appendDummyInput().appendField(new Blockly.FieldDropdown(a), "FLOW");
        this.setPreviousStatement(!0);
        var b = this;
        this.setTooltip(function () {
            var a = b.getFieldValue("FLOW");
            return {
                BREAK: Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK,
                CONTINUE: Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE
            }[a]
        })
    },
    onchange: function (a) {
        if (!this.workspace.isDragging()) {
            a = !1;
            var b = this;
            do {
                if (-1 != this.LOOP_TYPES.indexOf(b.type)) {
                    a = !0;
                    break
                }
                b = b.getSurroundParent()
            } while (b); a ? (this.setWarningText(null),
                this.isInFlyout || this.setDisabled(!1)) : (this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING),
                    this.isInFlyout || this.getInheritedDisabled() || this.setDisabled(!0))
        }
    },
    LOOP_TYPES: "controls_repeat_forever controls_repeat controls_repeat_ext controls_forEach controls_for controls_whileUntil tello_repeat_forever".split(" ")
};
// 获取原始积木定义
const originalIfBlock = Blockly.Blocks['controls_if'];

Blockly.Blocks.controls_if = {
    init: function () {
        originalIfBlock.init.call(this);
        this.setColour(CategoryColors.Logic);
    },
    
};
Blockly.Blocks.controls_if_elseif = {
    init: function () {
        this.setColour(CategoryColors.Logic);
        this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF);
        this.setPreviousStatement(!0);
        this.setNextStatement(!0);
        this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP);
        this.contextMenu = !1
    }
};
Blockly.Blocks.controls_if_else = {
    init: function () {
        this.setColour(CategoryColors.Logic);
        this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE);
        this.setPreviousStatement(!0);
        this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP);
        this.contextMenu = !1
    }
};
Blockly.Blocks.controls_if_if = {
    init: function () {
        this.setColour(CategoryColors.Logic);
        this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_IF_TITLE_IF);
        this.setNextStatement(!0);
        this.setTooltip(Blockly.Msg.CONTROLS_IF_IF_TOOLTIP);
        this.contextMenu = !1
    }
};
Blockly.Blocks['logic_compare'] = {
    /**
     * Block for comparison operator.
     * @this Blockly.Block
     */
    init: function () {
        var rtlOperators = [
            ['==', 'EQ'],
            ['!=', 'NEQ'],
            ['>', 'LT'],
            ['>=', 'LTE'],
            ['<', 'GT'],
            ['<=', 'GTE']
        ];
        var ltrOperators = [
            ['==', 'EQ'],
            ['!=', 'NEQ'],
            ['<', 'LT'],
            ['<=', 'LTE'],
            ['>', 'GT'],
            ['>=', 'GTE']
        ];
        var OPERATORS = this.RTL ? rtlOperators : ltrOperators;
        this.setHelpUrl(Blockly.Msg.LOGIC_COMPARE_HELPURL);
        this.setColour(CategoryColors.Logic);
        this.setOutput(true, 'Boolean');
        this.appendValueInput('A');
        this.appendValueInput('B')
            .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
        this.setInputsInline(true);
        // Assign 'this' to a variable for use in the tooltip closure below.
        var thisBlock = this;
        this.setTooltip(function () {
            var op = thisBlock.getFieldValue('OP');
            var TOOLTIPS = {
                'EQ': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ,
                'NEQ': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ,
                'LT': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT,
                'LTE': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE,
                'GT': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT,
                'GTE': Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE
            };
            return TOOLTIPS[op];
        });
        this.prevBlocks_ = [null, null];
    },
    /**
     * Called whenever anything on the workspace changes.
     * Prevent mismatched types from being compared.
     * @param {!Blockly.Events.Abstract} e Change event.
     * @this Blockly.Block
     */
    onchange: function (e) {
        var blockA = this.getInputTargetBlock('A');
        var blockB = this.getInputTargetBlock('B');
        // Disconnect blocks that existed prior to this change if they don't match.
        if (blockA && blockB &&
            !blockA.outputConnection.checkType_(blockB.outputConnection)) {
            // Mismatch between two inputs.  Disconnect previous and bump it away.
            // Ensure that any disconnections are grouped with the causing event.
            Blockly.Events.setGroup(e.group);
            for (var i = 0; i < this.prevBlocks_.length; i++) {
                var block = this.prevBlocks_[i];
                if (block === blockA || block === blockB) {
                    block.unplug();
                    block.bumpNeighbours_();
                }
            }
            Blockly.Events.setGroup(false);
        }
        this.prevBlocks_[0] = blockA;
        this.prevBlocks_[1] = blockB;
    }
};
Blockly.Blocks['logic_operation'] = {
    /**
     * Block for logical operations: 'and', 'or'.
     * @this Blockly.Block
     */
    init: function () {
        var OPERATORS =
            [[Blockly.Msg.LOGIC_OPERATION_AND, 'AND'],
            [Blockly.Msg.LOGIC_OPERATION_OR, 'OR']];
        this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
        this.setColour(CategoryColors.Logic);
        this.setOutput(true, 'Boolean');
        this.appendValueInput('A')
            .setCheck('Boolean');
        this.appendValueInput('B')
            .setCheck('Boolean')
            .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
        this.setInputsInline(true);
        // Assign 'this' to a variable for use in the tooltip closure below.
        var thisBlock = this;
        this.setTooltip(function () {
            var op = thisBlock.getFieldValue('OP');
            var TOOLTIPS = {
                'AND': Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND,
                'OR': Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR
            };
            return TOOLTIPS[op];
        });
    }
};

Blockly.Blocks['logic_negate'] = {
    /**
     * Block for negation.
     * @this Blockly.Block
     */
    init: function () {
        this.jsonInit({
            "message0": Blockly.Msg.LOGIC_NEGATE_TITLE,
            "args0": [
                {
                    "type": "input_value",
                    "name": "BOOL",
                    "check": "Boolean"
                }
            ],
            "output": "Boolean",
            "colour": CategoryColors.Logic,
            "tooltip": Blockly.Msg.LOGIC_NEGATE_TOOLTIP,
            "helpUrl": Blockly.Msg.LOGIC_NEGATE_HELPURL
        });
    }
};

Blockly.Blocks['logic_boolean'] = {
    /**
     * Block for boolean data type: true and false.
     * @this Blockly.Block
     */
    init: function () {
        this.jsonInit({
            "message0": "%1",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "BOOL",
                    "options": [
                        [Blockly.Msg.LOGIC_BOOLEAN_TRUE, "TRUE"],
                        [Blockly.Msg.LOGIC_BOOLEAN_FALSE, "FALSE"]
                    ]
                }
            ],
            "output": "Boolean",
            "colour": CategoryColors.Logic,
            "tooltip": Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP,
            "helpUrl": Blockly.Msg.LOGIC_BOOLEAN_HELPURL
        });
    }
};

Blockly.Blocks['logic_null'] = {
    /**
     * Block for null data type.
     * @this Blockly.Block
     */
    init: function () {
        this.jsonInit({
            "message0": Blockly.Msg.LOGIC_NULL,
            "output": null,
            "colour": CategoryColors.Logic,
            "tooltip": Blockly.Msg.LOGIC_NULL_TOOLTIP,
            "helpUrl": Blockly.Msg.LOGIC_NULL_HELPURL
        });
    }
};

Blockly.Blocks['logic_ternary'] = {
    /**
     * Block for ternary operator.
     * @this Blockly.Block
     */
    init: function () {
        this.setHelpUrl(Blockly.Msg.LOGIC_TERNARY_HELPURL);
        this.setColour(CategoryColors.Logic);
        this.appendValueInput('IF')
            .setCheck('Boolean')
            .appendField(Blockly.Msg.LOGIC_TERNARY_CONDITION);
        this.appendValueInput('THEN')
            .appendField(Blockly.Msg.LOGIC_TERNARY_IF_TRUE);
        this.appendValueInput('ELSE')
            .appendField(Blockly.Msg.LOGIC_TERNARY_IF_FALSE);
        this.setOutput(true);
        this.setTooltip(Blockly.Msg.LOGIC_TERNARY_TOOLTIP);
        this.prevParentConnection_ = null;
    },
    /**
     * Called whenever anything on the workspace changes.
     * Prevent mismatched types.
     * @param {!Blockly.Events.Abstract} e Change event.
     * @this Blockly.Block
     */
    onchange: function (e) {
        var blockA = this.getInputTargetBlock('THEN');
        var blockB = this.getInputTargetBlock('ELSE');
        var parentConnection = this.outputConnection.targetConnection;
        // Disconnect blocks that existed prior to this change if they don't match.
        if ((blockA || blockB) && parentConnection) {
            for (var i = 0; i < 2; i++) {
                var block = (i == 1) ? blockA : blockB;
                if (block && !block.outputConnection.checkType_(parentConnection)) {
                    // Ensure that any disconnections are grouped with the causing event.
                    Blockly.Events.setGroup(e.group);
                    if (parentConnection === this.prevParentConnection_) {
                        this.unplug();
                        parentConnection.getSourceBlock().bumpNeighbours_();
                    } else {
                        block.unplug();
                        block.bumpNeighbours_();
                    }
                    Blockly.Events.setGroup(false);
                }
            }
        }
        this.prevParentConnection_ = parentConnection;
    }
};

Blockly.Blocks['logic_isIn'] = {
    /**
     * Block for testing if something contains something.
     * @this Blockly.Block
     */
    init: function () {
        var OPERATORS =
            [["is in", 'IN'],
            ["is not in", 'NOTIN']];
        this.setColour(CategoryColors.Logic);
        this.setOutput(true, 'Boolean');
        this.appendValueInput('ITEM');
        this.appendValueInput('LIST')
            .setCheck(['Array', 'String'])
            .appendField(new Blockly.FieldDropdown(OPERATORS), 'OP');
        this.setInputsInline(true);
    }
};


Blockly.Blocks['logic_none'] = {
    /**
     * Block for testing if something contains something.
     * @this Blockly.Block
     */
    init: function () {
        this.appendDummyInput()
            .appendField("None");
        this.setColour(CategoryColors.Logic);
        this.setOutput(true);
    }
};
export default Blockly