import * as React from 'react';
import { ReactSVGPanZoom, Tool, Value, TOOL_PAN } from 'react-svg-pan-zoom';
import { Container } from './Elements/Container';
import { ContainerModel } from '../../Interfaces/ContainerModel';
import { Selector } from './Elements/Selector';

interface ISVGProps {
  width: number,
  height: number,
  children: ContainerModel | ContainerModel[] | null,
  selected: ContainerModel | null
}

interface ISVGState {
  value: Value,
  tool: Tool
}

export class SVG extends React.PureComponent<ISVGProps> {
  public state: ISVGState;
  public svg: React.RefObject<SVGSVGElement>;

  constructor(props: ISVGProps) {
    super(props);
    this.state = {
      value: {
        viewerWidth: window.innerWidth,
        viewerHeight: window.innerHeight
      } as Value,
      tool: TOOL_PAN
    };
    this.svg = React.createRef<SVGSVGElement>();
  }

  render() {
    const xmlns = '<http://www.w3.org/2000/svg>';

    const properties = {
      width: this.props.width,
      height: this.props.height,
      xmlns
    };

    let children: React.ReactNode | React.ReactNode[] = [];
    if (Array.isArray(this.props.children)) {
      children = this.props.children.map(child => <Container key={`container-${child.properties.id}`} model={child}/>);
    } else if (this.props.children !== null) {
      children = <Container key={`container-${this.props.children.properties.id}`} model={this.props.children}/>;
    }

    return (
      <ReactSVGPanZoom
        width={window.innerWidth}
        height={window.innerHeight}
        background={'#ffffff'}
        defaultTool='pan'
        value={this.state.value} onChangeValue={value => this.setState({ value })}
        tool={this.state.tool} onChangeTool={tool => this.setState({ tool })}
        miniatureProps={{
          position: 'left',
          background: '#616264',
          width: window.innerWidth - 12,
          height: 120
        }}
      >
        <svg ref={this.svg} {...properties}>
          { children }
          <Selector selected={this.props.selected} />
        </svg>
      </ReactSVGPanZoom>
    );
  };
}
