import extend from 'extend';

const KdWrapper = (Component) => {

  const createOptions = (props, render) => {
    let propTypes = {};

    for (var prop in Component.propTypes) {
      propTypes[prop] = undefined;
    }

    props = Object.assign({}, propTypes, props);

    for (const key in props) {
      let option = props[key];
      Object.defineProperty(props, key, {
        get() { return option; },
        set(value) {
          option = value;
          render();
        },
      });
    }
    return props;
  }

  return class ReactWrapper {
    constructor(props, container) {
      this.options = createOptions(props, this._render.bind(this));
      this._initialProps = extend(true, {}, props);
      this._container = container;
      this._render();
    }

    _render() {
      this._renderedComponent = ReactDOM.render(
        React.createElement(Component, this.options, null),
        this._container
      );
    }

    set(property, value) {
      this.options[property] = value;
      this._render();
    }

    getOption(property) {
      return this.options[property];
    }

    setOptions(props) {
      this.options = Object.assign({}, this.options, props);
      this._render();
    }

    get(method) {
      return this._renderedComponent[method]();
    }

    disable() {
      return this.set('isDisabled', true);
    }

    enable() {
      return this.set('isDisabled', false);
    }

    reset(){
      this.destroy();
      this.options = createOptions(extend(true, {}, this._initialProps), this._render.bind(this));
      this._render();
    }

    destroy() {
      ReactDOM.unmountComponentAtNode(this._container);
    }
  }
}

export default KdWrapper;