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

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

class ReactTabGroupSection extends React.Component {

  /**
   * Define default properties.
   * 
   * @type {Object}
   */
  static defaultProps = {
    className: null,
    content: 'section'
  };

  /**
   * Set properties type.
   * 
   * @type {Object}
   */
  static propTypes = {
    className: React.PropTypes.string,
    content: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.object
    ])
  };

  displayName = 'ReactTabGroupSection';

  constructor(props) {
    super(props);
    
    let async = $.isPlainObject(props.content);

    this.state = {
      loading: async,
      content: async ? null : props.content,
      requested: ! async
    };
  }

  /**
   * Fetch content.
   * 
   * @return {undefined}
   */
  request(config) {
    if (!this.state.requested) {
      $.getJSON(config.url, config.params)
       .then((response) => {
          if (response.code === 0) {
            this.setState({
              loading: false,
              content: response.result,
              requested: true
            });
          }
        });
    }
  }

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

  componentWillReceiveProps(props) {
    let async = $.isPlainObject(props.content);

    this.state.loading    = async;
    this.state.requested  = ! async;

    if ($.isPlainObject(props.content)) {
      this.request(props.content);
    } else if ($.type(props.content) === 'string') {
      this.state.content = props.content;
    }
  }

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

export default ReactTabGroupSection;
