import { Component, OnInit } from '@angular/core';
import Blockly from 'node-blockly/browser';
import { ScriptService } from './scripts.service';
@Component({
selector: 'app-scripts',
templateUrl: './scripts.component.html',
styleUrls: ['./scripts.component.css']
})
export class ScriptsComponent implements OnInit {
constructor(private scriptservice: ScriptService) {
}
private code: string;
private xml: string;
private _scripts: any[];
private workspace;
private editor;
private _script_id: number;
toolbox = `<xml id="toolbox" style="display: none">
<category name="Logic">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="logic_operation"></block>
<block type="logic_negate"></block>
<block type="logic_boolean"></block>
<block type="logic_test"></block>
<block type="logic_test2"></block>
</category>
<category name="Loops">
<block type="controls_repeat_ext">
<value name="TIMES">
<block type="math_number">
<field name="NUM">10</field>
</block>
</value>
</block>
<block type="controls_whileUntil"></block>
</category>
<category name="Math">
<block type="math_number"></block>
<block type="math_arithmetic"></block>
<block type="math_single"></block>
<block type="math_toto"></block>
</category>
<category name="Text">
<block type="text"></block>
<block type="text_length"></block>
<block type="text_print"></block>
</category>
</xml>`;
ngOnInit() {
const self = this;
this.workspace = new Blockly.Workspace();
this.editor = Blockly.inject('editor', {
toolbox: this.toolbox
});
this.scriptservice.loadScripts()
.then(
response => {
if (response != null) {
self._scripts = [];
for (const i in response) {
if (response[i] != null) {
const script = response[i];
self._scripts.push(
{
id: script.script_id,
text: script.script_name
}
);
}
}
}
}
);
const xml = Blockly.Xml.textToDom(localStorage.getItem('script'));
Blockly.Xml.domToWorkspace(xml, this.editor);
}
onScriptSelect(event) {
const self = this;
this.scriptservice.loadScript(event.id)
.then(
response => {
Blockly.getMainWorkspace().clear();
const xml = Blockly.Xml.textToDom(response);
Blockly.Xml.domToWorkspace(xml, this.editor);
self._script_id = event.id;
}
);
}
saveScript() {
const xml = Blockly.Xml.workspaceToDom(this.editor);
const xml_text = Blockly.Xml.domToText(xml);
localStorage.setItem('script', xml_text);
this.scriptservice.saveScript(this._script_id, xml_text);
}
clearScript() {
Blockly.getMainWorkspace().clear();
}
}