import React from 'react';
import { autobind } from 'core-decorators';
import { getPageData } from '../service/CacheService';
import InfoException from '../modules/exception/InfoException';

const AsyncDecorator = Wrapper => {
  class WrapperComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: this.props.dataSource || getPageData()
      };
    }

    @autobind
    freshData(data) {
      this.setState({ data });
    }

    componentDidMount() {
      const mainContent = document.querySelector('.main-content');
      if (mainContent) {
        this.mainContentHeight = mainContent.style.height;
        mainContent.style.height = '100%';
      }
    }

    componentWillUnmount() {
      const mainContent = document.querySelector('.main-content');
      if (mainContent) {
        mainContent.style.height = this.mainContentHeight;
      }
    }

    render() {
      const { data } = this.state;
      if (data === 'EXCEPTION') {
        return (
          <InfoException />
        );
      }
      return (
        <Wrapper
          {...this.props}
          dataSource={data}
          freshData={this.freshData}
        />
      );
    }
  }

  return WrapperComponent;
};

export default AsyncDecorator;

