import React, { Component } from 'react';
import { amosRequest } from 'amos-processor';

/**
 * sync component
 *
 * @param {any} WrapperComponent
 * @param {any} options : { url, params: { method, body, header } }
 * @returns enhance Component
 */
export default function(WrapperComponent, options) {
  const _options = Object.assign(
    {},
    {
      method: 'get'
    },
    options
  );

  const { url, method, data, params } = _options;

  const newOptions = {
    method,
    ...params
  };

  if (method === 'POST' || method === 'PUT') {
    newOptions.body = JSON.stringify(data);
  }

  class FetchComponent extends Component {
    constructor(props) {
      super(props);
      this.state = {
        dataList: null
      };
    }

    componentWillMount() {
      amosRequest(url, newOptions).then(data =>
        this.setState({
          dataList: data
        })
      );
    }

    reload = data => {
      let _params = {};
      data &&
        (_params = {
          body: data
        });
      amosRequest(url, _params).then(data =>
        this.setState({
          dataList: data
        })
      );
    };

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

      return <WrapperComponent dataList={dataList} reload={this.reload} {...this.props} />;
    }
  }

  return FetchComponent;
}
