import * as Blockly from 'blockly';
import { pythonGenerator } from "blockly/python";

Blockly.Python = pythonGenerator || { Msg: Object.create(null) }


Blockly.Python['time_delay'] = function(block) {
    Blockly.Python.definitions_['import_time'] = 'import time';
    var delayTime = Blockly.Python.valueToCode(
        block, 'DELAY_TIME_MILI', Blockly.Python.ORDER_ATOMIC) || '0';
    var code = 'time.sleep(' + delayTime + ');\n';
    return code;
};


Blockly.Python['time_delayseconds'] = function(block) {
    // var time_type = block.getFieldValue('type');

    Blockly.Python.definitions_['import_time'] = 'import time';
    var delayTimeMs = Blockly.Python.valueToCode(
        block, 'DELAY_TIME_MICRO', Blockly.Python.ORDER_ATOMIC) || '0';
    var code = 'time.sleep(' + delayTimeMs + ')\n';

    return code;
};

Blockly.Python['esp32_get_current_date'] = function (block) {
    var dropdown_type = block.getFieldValue('type');

    // Blockly.Python.definitions_['v831_import_time'] = `from datetime import date`
    Blockly.Python.definitions_['import_datetime_datetime'] = `from datetime import datetime`
    Blockly.Python.definitions_['get_current_date'] = `def getCurrent_data(type):
    now = datetime.now()
    return now.strftime("%"+type+"")
`
    // TODO: Assemble Python into code variable.
    var code = `getCurrent_data("${dropdown_type}")`
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Python['esp32_main_controller_time_timer_init'] = function (block) {
    var timer_type = block.getFieldValue('type');

    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['counter_start_variable'] = `counter_start = 0 
def counter_start_fun():
    global counter_start
    counter_start = time.perf_counter()
`;
    var code = `counter_start_fun() \n`;
    return code;
};

Blockly.Python['esp32_main_controller_time_timer_get_current'] = function (block) {
    Blockly.Python.definitions_['counter_end'] = `def getcounterEndStart(newDate):
    global counter_start
    return newDate - counter_start
`
    var code = `getcounterEndStart(time.perf_counter())`;
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Python['esp32_main_controller_time_timer_clear'] = function (block) {
    var code = `del counter_start
`;
    return code;
};

Blockly.Python['esp32_main_controller_time_period_timer'] = function (block) {
    var text_period_timer_count = block.getFieldValue('period_timer_count') * 0.001;
    var statements_name = Blockly.Python.statementToCode(block, 'exec_period_timer');
    Blockly.Python.addVariable("STOPTHREAD", "STOPTHREAD = False", true)
    Blockly.Python.definitions_['import_threading'] = `import threading`
    Blockly.Python.definitions_['import_time'] = `import time`
    
    let global = ""
    try {
        let allBlocks = Blockly.getMainWorkspace().variableMap.getAllVariableNames()
        global = allBlocks.join()
    }
    catch (e) {
        console.log(e)
    }
    Blockly.Python.definitions_['v831_import_thread_calsss'] = `def period_timer_count(n: int):
    global STOPTHREAD
    while True:
        if STOPTHREAD:
            break
        time.sleep(${text_period_timer_count})
        thread_calsss_fun_timer()
`
    Blockly.Python.definitions_['v831_import_thread_calsss_fun'] = `def thread_calsss_fun_timer():
    global ${global}
${statements_name}
`
    var code = `CocoPiThread = threading.Thread(target=period_timer_count, args=(1,))
CocoPiThread.start()
`
    return code;
};

Blockly.Python['esp32_main_controller_time_period_timer_clear'] = function (block) {
    var code = `STOPTHREAD = True
`
    return code;
};

Blockly.Python.addVariable = function (varName, code, overwrite) {
  var overwritten = false;
  if (overwrite || (Blockly.Python.variableDB_.dbReverse_[varName] === undefined)) {
    // Blockly.Python.definitions_[varName] = code;
    // 创建变量并生成对应的变量积木
    if (Blockly && Blockly.Variables && Blockly.getMainWorkspace) {
      const workspace = Blockly.getMainWorkspace();
      if (workspace && !workspace.getVariable(varName)) {
        // Blockly.Python.variables_[varName] = code;
        workspace.createVariable(varName);
      }
    }
    overwritten = true;
  }
  return overwritten;
};
export default Blockly;