/**
 * @file        Surface component
 * @author      MicroMatrix <yangpan.1985@bytedance.com>
 * @copyright   2012-2020 bytedance
 * @link        git@code.byted.org:yangpan.1985/avg.git
 */

import React from 'react';
import PropTypes from 'prop-types';
import ReactUpdates from 'react-dom/lib/ReactUpdates';
import ReactInstanceMap from 'react-dom/lib/ReactInstanceMap';
import ContainerMixin from 'components/ContainerMixin';

import core from 'core/core';

/**
 * Surface is a standard React component and acts as the main drawing canvas.
 * ReactCanvas components cannot be rendered outside a Surface.
 */
export class Surface extends React.PureComponent {
  // mixins: [ContainerMixin],
  static propTypes = {
    children: PropTypes.any
  };
  constructor(props) {
    super(props);

    Object.assign(this, ContainerMixin);
  }
  componentDidMount() {
    this.node = core.getStage();

    // This is the integration point between custom canvas components and React
    const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();

    transaction.perform(
      this.mountAndInjectChildren,
      this,
      this.props.children,
      transaction,
      ReactInstanceMap.get(this)._context
    );
    ReactUpdates.ReactReconcileTransaction.release(transaction);
  }

  componentDidUpdate() {
    // We have to manually apply child reconciliation since child are not
    const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();

    transaction.perform(
      this.updateChildren,
      this,
      this.props.children,
      transaction,
      ReactInstanceMap.get(this)._context
    );
    ReactUpdates.ReactReconcileTransaction.release(transaction);
  }

  componentWillUnmount() {
    // Implemented in ReactMultiChild.Mixin
    this.unmountChildren();
    this.node.removeChildren();
  }

  render() {
    return null;
  }
}

// module.exports = Surface;
