import Blockly, { Xml } from 'blockly';
const bct = require('@blockly/continuous-toolbox');
import './blockly-vex';

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, {
      plugins: {
        toolbox: bct.ContinuousToolbox,
        flyoutsVerticalToolbox: bct.ContinuousFlyout,
        metricsManager: bct.ContinuousMetrics,
      },
      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));
  }

  /**
   * 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);
  }
}
