/**
 * @author Martin Karkowski
 * @email m.karkowski@zema.de
 * @create date 2021-07-22 11:16:03
 * @modify date 2021-07-22 11:16:03
 * @desc [description]
 */

import * as go from "gojs";
import { ReactPalette } from "gojs-react";
import * as React from "react";

interface PaletteProps {
  nodeTemplates: {
    name: string;
    template: go.Part;
    sampleData: any;
  }[];
}

/**
 * Renders a Palette.
 */
export class PaletteWrapper extends React.Component<PaletteProps, never> {
  /**
   * Ref to keep a reference to the Diagram component, which provides access to the GoJS diagram via getDiagram().
   */
  private paletteRef: React.RefObject<ReactPalette>;

  /** @internal */
  constructor(props: PaletteProps) {
    super(props);
    this.paletteRef = React.createRef();
  }

  public componentDidMount(): void {
    if (!this.paletteRef.current) return;
    const palette = this.paletteRef.current.getPalette();

    // Adapt its size
    palette.div.style.height = "100%";
    palette.div.style.width = "100%";
  }

  public render(): JSX.Element {
    // Firstly, we extract the Template
    const _nodeTemplates = Array.isArray(this.props.nodeTemplates)
      ? this.props.nodeTemplates
      : [];
    // Inhere we store the Sample-Data of the Elements.
    const _renderedTemplates = _nodeTemplates.map((item) => item.sampleData);

    // Now we use the Go-JS Palette Element to render our Palette
    return (
      <ReactPalette
        ref={this.paletteRef}
        initPalette={(...args) => {
          const paletteObject = new go.Palette();
          // the list of data to show in the Palette

          for (const item of _nodeTemplates) {
            paletteObject.nodeTemplateMap.add(item.name, item.template);
          }

          return paletteObject;
        }}
        divClassName="none"
        nodeDataArray={_renderedTemplates}
      ></ReactPalette>
    );
  }
}
