import Blockly, { Xml } from 'blockly';
import 'blockly/javascript';
import './blockly-vex';

// Blockの読み込み
import './blocks/js-c-block';
import './generators/js-c-block';

Blockly.HSV_SATURATION = 0.8;
Blockly.HSV_VALUE = 0.85;

export class BlocklyApp {
  readonly workspace: Blockly.WorkspaceSvg;

  constructor(parent: string | Element, toolbox: string) {
    this.workspace = Blockly.inject(parent, {
      toolbox: Xml.textToDom(toolbox),
      media: 'blockly-media/',
      renderer: 'zelos',
      theme: Blockly.Theme.defineTheme('ClassicHats', {
        base: Blockly.Themes.Classic,
        startHats: true,
      }),
    });
    window.addEventListener('resize', () => Blockly.svgResize(this.workspace));
    this.workspace.addChangeListener(Blockly.Events.disableOrphans);
    this.setWorkspaceText(require('./default-workspace.xml?raw'));
  }

  /**
   * Blocklyのワークスペースを文字列に変換します。
   * setWorkspaceTextを使うことで復元できます
   */
  getWorkspaceText(): string {
    return Xml.domToText(Xml.workspaceToDom(this.workspace));
  }

  /**
   * Blocklyのワークスペースを設定します
   */
  setWorkspaceText(xmlText: string) {
    this.workspace.clear();
    Xml.domToWorkspace(Xml.textToDom(xmlText), this.workspace);
  }

  getCode(): string {
    const contents = Blockly.JavaScript.workspaceToCode(this.workspace)
      // インデントの追加
      .replace(/\n([^\n])/g, '\n  $1');

    return `#include <iostream>
#include <cstdint>

int main(int argc, char *argv[])
{
  ${contents}
  return 0;
}
`;
  }

  setVisible(visible: boolean) {
    this.workspace.setVisible(visible);
  }
}
