/**
 * imui.Form
 * @author moxhe
 * @date 2016-08-08
 */

/**
 * 主要功能
 * 1. 表单排布
 * 2. 利用context构造API
 */

import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

export default class Form extends React.Component {
  static propTypes = {
    /**
     * FormRow之间是否水平
     */
    inline: PropTypes.bool,
    /**
     * 表单与Label排布是否水平
     */
    horizontal: PropTypes.bool,
    // onSubmit: PropTypes.func
  };

  static defaultProps = {
    prefixCls: 'im-form',
    horizontal: true,
  };

  static childContextTypes = {
    form: PropTypes.object,
  };

  getChildContext() {
    return { form: this };
  }

  constructor(props) {
    super(props);

    this.fields = {};

    this.getValues = this.getValues.bind(this);
    this.setValues = this.setValues.bind(this);
    this.getFieldValue = this.getFieldValue.bind(this);
    this.setFieldValue = this.setFieldValue.bind(this);
  }

  // APIs
  getValues() {
    const result = {};

    Object.keys(this.fields).forEach((name) => {
      result[name] = this.getFieldValue(name);
    });

    return result;
  }

  setValues(values) {
    Object.keys(values).forEach((name) => {
      this.setFieldValue(name, values[name]);
    });
  }

  getFieldValue(name) {
    const field = this.fields[name];

    if (field && field.getValue) {
      return field.getValue();
    }

    return null;
  }

  setFieldValue(name, value) {
    const field = this.fields[name];

    if (field && field.setValue) {
      field.setValue(value);
      return true;
    }

    return false;
  }

  render() {
    const { prefixCls, className, inline, horizontal } = this.props;

    const allCls = {
      [prefixCls]: true,
      [className]: !!className,
      [`${prefixCls}--h`]: horizontal,
      [`${prefixCls}--inline`]: inline,
    };

    return (
      <form className={classnames(allCls)}>{this.props.children}</form>
    );
  }
}
