import Blockly from "blockly";
import { Cpp, ORDER_ASSIGNMENT, ORDER_ATOMIC } from "./cpp";


Cpp['variables_get'] = block => {
  const varBlock = block.getFieldValue('VAR');
  const code = Cpp.nameDB_.getName(varBlock, Blockly.VARIABLE_CATEGORY_NAME);
  return [code, ORDER_ATOMIC];
}

Cpp['variables_set'] = block => {
  const varBlock = block.getFieldValue('VAR');
  const varName = Cpp.nameDB_.getName(varBlock, Blockly.VARIABLE_CATEGORY_NAME);
  const varModel = block.workspace.getVariableById(varBlock);
  if (!varModel) throw new Error(`${varBlock} not found.`);

  const ctype = Cpp.getType(varModel.type);
  if (!ctype) throw new Error(`${varBlock.type} is not defined`);

  const value = Cpp.valueToCode(block, 'VALUE', ORDER_ASSIGNMENT) || ctype.defaultValue;
  return `${varName} = ${value};\n`;
}
Cpp['variables_get_dynamic'] = Cpp['variables_get'];
Cpp['variables_set_dynamic'] = Cpp['variables_set'];

