'use strict';

var workspace = null;

// - variables set in cpp
var job = null;
var boardFactory = null;
var moduleFactory = null;
var widget = null;


hljs.initHighlightingOnLoad();

function updateLogic() {
    var xml = job.logic.xml;
    try {
        var xmlDom = Blockly.Xml.textToDom(xml);
    } catch (e) {
        alert("逻辑转换失败");
    }

    workspace.clear();
    Blockly.Xml.domToWorkspace(workspace, xmlDom);
}

function updateCodePage (code) {
    $('#code-box code').text(code);
    hljs.initHighlighting.called = false;
    hljs.initHighlighting();

    $('.hljs-line-numbers').remove();
    $('code.hljs').each(function(i, block) {
        hljs.lineNumbersBlock(block);
    });
}

function saveLogicToJob(xml, code) {
    if (!job) return;

    var logic = job.logic;

    logic.xml = xml;
    logic.code = code;
}

function addClearFlagsBlockIfNeeded() {
    var xmlDom = Blockly.Xml.workspaceToDom(workspace);

}

function onLogicChange() {
    var xmlDom = Blockly.Xml.workspaceToDom(workspace);
    var xml = Blockly.Xml.domToText(xmlDom);

    if ($(xmlDom).find('[type="set_code_check_flag"]').length !== 0) {
        $(xmlDom).append('<block type="clear_code_check_flag" id="clear_code_check_flag_block_id"></block>');
        var workspaceTemp = new Blockly.Workspace();
        Blockly.Xml.domToWorkspace(xmlDom, workspaceTemp);
        var code = Blockly.Arduino.workspaceToCode(workspaceTemp);

    } else {
        var code = Blockly.Arduino.workspaceToCode(workspace);
   }

    updateCodePage(code);
    saveLogicToJob(xml, code);
}

$(document).ready(function() {
    workspace = Blockly.inject('blocklyDiv', {
            grid: {
                spacing: 25,
                length: 5,
                color: '#ccc',
                snap: true
            },
            media: 'blockly/media/',
            toolbox: document.getElementById('toolbox'),
            zoom: {
                 controls:  true,
                 wheel: true
            },
    });

    workspace.addChangeListener(onLogicChange);

    $('.tabs .tab-header a').on('click', function (e) {
        var currentAttr = $(this).attr('href');
        $('.tabs ' + currentAttr).show().siblings().hide();
        $(this).parent('li').addClass('active').siblings().removeClass('active');

        if (currentAttr == '#tab-blockly') {
            workspace.setVisible(true);
        } else {
            workspace.setVisible(false);
        }

        e.preventDefault();
    });

    var onResize = function(e) {
        var tabHeaderHeight = $('#main-tab-header').outerHeight();
        $('#main-tab-content').css("height", ($(document.body).outerHeight() - tabHeaderHeight - 10) + "px");
        $('#main-tab-content').height($(document.body).outerHeight() - tabHeaderHeight - 10);
    };

    $(window).resize(onResize);
    onResize();

    $('#code-check-button').on('click', function(e) {
        if (widget) {
            widget.emitCodeCheck();
        }

        e.preventDefault();
    });

    onLogicChange();
});


function updateToolbox() {
    var toolboxXML = $('#toolbox');
    var modulesCategoryXML = toolboxXML.children("#connected-modules");
    modulesCategoryXML.empty();

    var pins = job.board.jsPins;
    var boardDef = boardFactory.boardDefOfType(job.board.type);

    var count = 0;
    for (var i = 0; i < pins.length; ++i) {
        var pin = pins[i];
        var pinDef = boardDef.defOfPin(pin.name);

        if (pin.module) {
            var moduleDef = moduleFactory.moduleDefOfType(pin.module.type);
            var blockXMLPrefix = '<block type="' + moduleDef.blocklyBlock + '">';
            var blockXMLPostfix = '</block>';
            var blockXMLField = '<field name="PIN">' + pinDef.ref + '</field>';

            if (moduleDef.dualPin) {
                ++i;
                var pin2 = pins[i];
                var pin2Def = boardDef.defOfPin(pin2.name);

                blockXMLField += '<field name="PIN2">' + pin2Def.ref + '</field>';
            }

            if (pinDef.capableModule.pinType == 3) {
                blockXMLField += '<mutation hardware_i2c="true"></mutation>';
            }

            modulesCategoryXML.append(blockXMLPrefix + blockXMLField + blockXMLPostfix);
            count++;
        }
    }

    modulesCategoryXML.attr("name", "已连接模块（" + count + "）");
    workspace.updateToolbox(toolboxXML.get(0));
}
