
import React, { useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { updateBlocklyCode, updateBlocklyXml, updateBlocklyLength } from '../states/global';
import './BlocklyComponent.css';

import * as Blockly from 'blockly';
import { pythonGenerator } from 'blockly/python';
import hans from './msg/zh-hans';
import hant from './msg/zh-hant';
import en from './msg/en';
import 'blockly/blocks';
import BlocklyStyle from './style/blockly';
import pythonCode from './generator/index';
import BlockXmls from './blocklyXml';

// Blockly.setLocale(locale);

function BlocklyComponent(props) {
  const dispatch = useDispatch();
  const blocklyXml = useSelector(state => state.blocklyXml);
  const blocklyDiv = useRef();
  let primaryWorkspace = useRef();

  const generateCode = () => {
    var code = pythonCode.Python.workspaceToCode(primaryWorkspace.current);
    dispatch(updateBlocklyCode(code));
  };

  useEffect(() => {
    let BlocklyXmls = Blockly.utils.xml.textToDom(BlockXmls);
    var categoryNodes = BlocklyXmls.getElementsByTagName('category');
    for (var i = 0; i < categoryNodes.length; i++) {
      var cat = categoryNodes[i];
      var catId = cat.getAttribute('id');
      var catText = hans[catId] || catId;
      if (catText) {
        cat.setAttribute('name', catText);
      }
    }
    Blockly.setLocale(hans);
    if (!primaryWorkspace.current) {
      initBlockly(BlocklyXmls);
    }
    if (blocklyXml === `<xml xmlns="https://developers.google.com/blockly/xml"></xml>`) {
      // 清除积木
      clearWorkspace();
    }
  }, [blocklyXml]);

  const getBlocklXml = () => {
    console.log("getBlocklXml")
    // Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(blocklyXml), primaryWorkspace.current);
    // getWorkspaceXml()
  }

  const initBlockly = (xmls) => {
    const workspace = Blockly.inject(blocklyDiv.current, {
      media: 'media/',
      toolbox: xmls,
      theme: BlocklyStyle,
      collapse: true,
      comments: true,
      css: true,
      disable: true,
      grid: false,
      maxBlocks: Infinity,
      rtl: false,
      scrollbars: true,
      sounds: true,
      trashcan: true,
      zoom: {
        controls: true,
        wheel: false,
        startScale: 1.0,
        maxScale: 2,
        minScale: 0.2,
        scaleSpeed: 1.2
      },
    });
    primaryWorkspace.current = workspace;
    window.blockly = workspace;
    window.Blockly = Blockly;
    primaryWorkspace.current.addChangeListener(addBlocklyEventListeners);
    if (localStorage.getItem('workspaceXml')) {
      // 加载本地存储保存的积木
      getLocalStorageXml();
    };
  };

  const addBlocklyEventListeners = (event) => {
    getWorkspaceXml();
    // 积木区域操作是生成代码
    generateCode();
  };
  const getWorkspaceXml = () => {
    // console.log('getWorkspaceXml',Blockly.Xml.workspaceToDom(primaryWorkspace.current))
    var blockCount = primaryWorkspace.current.getAllBlocks(false).length;
    var xml = Blockly.Xml.domToText(Blockly.Xml.workspaceToDom(primaryWorkspace.current));
    dispatch(updateBlocklyXml(xml));
    dispatch(updateBlocklyLength(blockCount));
  };
  // 清除积木
  const clearWorkspace = () => {
    primaryWorkspace.current.clear();
  };

  const getLocalStorageXml = () => {
    let xml = localStorage.getItem('workspaceXml');
    if (xml) {
      Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(xml), primaryWorkspace.current);
      getWorkspaceXml()
    }
  };

  return (<React.Fragment>
    <div ref={blocklyDiv} id="blocklyDiv" />
  </React.Fragment>
  );
}

export default BlocklyComponent;