/**
 * Tabbar section for Tabbar component.
 * @author Artisan
 * created at 2015-10-19
 */

import $ from 'jquery';
import React from 'react';
import classnames from 'classnames';

class TabbarSection extends React.Component {
  constructor(props) {
    super(props);
    const async = $.isPlainObject(props.content);
    this.state = {
      loading: async,
      content: async ? null : props.content
    };
    this.displayName = 'TabbarSection';
  }

  /**
   * Fetch content.
   * @return {Undefined}
   */
  request() {
    const {content} = this.props;
    
    if ( $.type(content.url) === 'string' ) {
      const xmlHttpRequest = $.getJSON(content.url, content.params);

      xmlHttpRequest.then((response) => {
        if (response.code === 0) {
          this.setState({
            content: response.result,
            loading: false
          });
        }
      });
    }
  }

  componentDidMount() {
    if (this.state.loading) {
      this.request();
    }
  }

  componentDidUpdate(props) {
    if (this.state.loading) {
      this.request();
    } 
  }

  render() {
    return (
      <div className={ classnames('tabbar-body', this.props.className) } dangerouslySetInnerHTML={{ __html: this.state.content }}></div>
    );
  }
}

// Set default properties.
TabbarSection.defaultProps = {
  className: null,
  content: 'section'
};

// Set default 
TabbarSection.propTypes = {
  className: React.PropTypes.string,
  content: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.object
  ])
};

export default TabbarSection;
