/**
 * @fileoverview Utility module for useCodeGeneration.js
 * 
 * @module pages.Playground.hooks.useCodeGeneration
 */

import { useMemo } from "react";
import * as Blockly from "blockly/core";
import { javascriptGenerator } from "blockly/javascript";
import { pythonGenerator } from "blockly/python";

export const useCodeGeneration = (workspace, version = 0) => {
  return useMemo(() => {
    if (!workspace) {
      return {
        javascript: "",
        python: "",
      };
    }

    try {
      javascriptGenerator.STATEMENT_PREFIX = null;
      javascriptGenerator.STATEMENT_SUFFIX = null;
      javascriptGenerator.INFINITE_LOOP_TRAP = null;

      pythonGenerator.STATEMENT_PREFIX = null;
      pythonGenerator.STATEMENT_SUFFIX = null;
      pythonGenerator.INFINITE_LOOP_TRAP = null;

      const javascript = javascriptGenerator.workspaceToCode(workspace);
      const python = pythonGenerator.workspaceToCode(workspace);

      return {
        javascript,
        python,
      };
    } catch (error) {
      console.error("Erro ao gerar código:", error);
      return {
        javascript: `// Erro ao gerar código: ${error.message}`,
        python: `# Erro ao gerar código: ${error.message}`,
      };
    }
  }, [workspace, version]);
};
