/**
 * @license
 * Copyright 2020 Sébastien CANET
 * SPDX-License-Identifier: BSD-3-Clause
 */

/**
 * @fileoverview Generating Arduino code for loop blocks.
 * @author scanet@libreduc.cc (Sébastien CANET)
 */
 
'use strict';

goog.provide('Blockly.Arduino.loops');

goog.require('Blockly.Arduino');


Blockly.Arduino['controls_repeat_ext'] = function (block) {
    // Repeat n times.
    if (block.getField('TIMES')) {
        // Internal number.
        var repeats = String(Number(block.getFieldValue('TIMES')));
    } else {
        // External number.
        var repeats = Blockly.Arduino.valueToCode(block, 'TIMES',
                Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
    }
    var branch = Blockly.Arduino.statementToCode(block, 'DO');
    branch = Blockly.Arduino.addLoopTrap(branch, block.id);
    var code = '';
    var loopVar = Blockly.Arduino.variableDB_.getDistinctName(
            'count', Blockly.Variables.NAME_TYPE);
    var endVar = repeats;
    if (!repeats.match(/^\w+$/) && !Blockly.isNumber(repeats)) {
        var endVar = Blockly.Arduino.variableDB_.getDistinctName(
                'repeat_end', Blockly.Variables.NAME_TYPE);
        code += 'int ' + endVar + ' = ' + repeats + ';\n';
    }
    code += 'for (int ' + loopVar + ' = 0; ' +
            loopVar + ' < ' + endVar + '; ' +
            loopVar + '++) {\n' +
            branch + '}\n';
    return code;
};

Blockly.Arduino['controls_repeat'] =
        Blockly.Arduino['controls_repeat_ext'];

Blockly.Arduino['controls_whileUntil'] = function (block) {
    // Do while/until loop.
    var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL', Blockly.Arduino.ORDER_NONE) || 'false';
    var branch = Blockly.Arduino.statementToCode(this, 'DO');
    if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
        branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
                '\'' + this.id + '\'') + branch;
    }
    if (this.getFieldValue('MODE') == 'UNTIL') {
        if (!argument0.match(/^\w+$/)) {
            argument0 = '(' + argument0 + ')';
        }
        argument0 = '!' + argument0;
    }
    return 'while (' + argument0 + ') {\n' + branch + '}\n';
};

Blockly.Arduino['controls_for'] = function(block) {
    // Если в VAR ничего нет — вернётся пустая строка и используется NAN
    var varName = Blockly.Arduino.valueToCode(block, 'VAR', Blockly.Arduino.ORDER_ATOMIC) || 'NAN';
    var from    = Blockly.Arduino.valueToCode(block, 'FROM', Blockly.Arduino.ORDER_ASSIGNMENT)   || '0';
    var to      = Blockly.Arduino.valueToCode(block, 'TO',   Blockly.Arduino.ORDER_RELATIONAL)   || '0';
    var dir     = block.getFieldValue('DIR');
    var by      = Blockly.Arduino.valueToCode(block, 'BY',   Blockly.Arduino.ORDER_ADDITIVE)     || '1';
    var body    = Blockly.Arduino.statementToCode(block, 'DO');
    
    var code = '';
    if (dir === "+") {
        code = 
            'for (' + varName + ' = ' + from + '; '
                    + varName + ' <= ' + to   + '; '
                    + varName + ' += ' + by   + ') {\n'
            + body
            + '}\n';
    } else {
        code = 
            'for (' + varName + ' = ' + from + '; '
                    + varName + ' >= ' + to + '; '
                    + varName + ' -= ' + by + ') {\n'
            + body
            + '}\n';
    }
    return code;
};

Blockly.Arduino['controls_flow_statements'] = function (block) {
    // Flow statements: continue, break.
    switch (block.getFieldValue('FLOW')) {
        case 'BREAK':
            return 'break;\n';
        case 'CONTINUE':
            return 'continue;\n';
    }
    throw 'Unknown flow statement.';
};
