/* eslint-disable */
import React from 'react';
import template from 'lodash.template';
import { componentNodeMap, getComponentNode } from '../../componentNodeMap';

export class JimuAdaptor extends React.PureComponent {
  view = null;

  template = null;

  jimuInstance = null;

  hasInited = false;

  node = null;

  constructor(props) {
    super(props);

    const {
      instance: {
        component: { component },
      },
    } = props;
    this.view = component;
    this.template = template(this.view.template);
    this.jimuInstance = new this.view.component();
  }

  componentWillReceiveProps({ instance: nextInstance }) {
    if (!this.node) {
      return;
    }

    this.renderComponent(this.node, nextInstance);
  }

  setNode = node => {
    this.node = node;

    if (!this.hasInited) {
      this.renderComponent(this.node, this.props.instance);
    }
  };

  renderComponent = (node, instance) => {
    const { key, style, data, commonStyle } = instance;
    const props = { id: `jimu-adaptor-${key}`, ...data, it: data, style, commonStyle };

    const externalProps = {
      global: this.props.global,
      meta: this.props.meta,
      style,
      commonStyle,
      componentsMap: componentNodeMap,
      getComponentByKey: getComponentNode,
    };

    const updateTemplate =
      style !== this.props.instance.style || commonStyle !== this.props.instance.commonStyle;

    if (updateTemplate || !this.hasInited) {
      node.innerHTML = this.template(props);
      this.jimuInstance = new this.view.component();
      this.jimuInstance.init(props, externalProps);
      this.hasInited = true;
    } else {
      this.jimuInstance.refreshData(props, externalProps);
    }
  };

  render() {
    return <div ref={this.setNode} />;
  }
}
