import React, { Component, cloneElement, Children } from 'react';
import PropTypes from 'prop-types';
import loadScripts from 'dt2react/lib/utils/loadScripts';


class WithGlobalComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loaded: false
    }

    this.init();
  }

  init = () => {
    const { scripts } = this.props;

    if (scripts) {
      loadScripts.loadAllByPromise(scripts).then(
        () => {
          this.setState({
            loaded: true
          });
        }
      );
    }
  }

  render() {
    const { loaded } = this.state;

    return Children.map(this.props.children, (Child) => {
      if (!Child){
        return;
      }

      return cloneElement(Child, {
        loaded
      });
    });

  }
}

export default WithGlobalComponent;
