/** @jsx createElement */

'use strict';

import {
  createElement,
  Component,
  isValidElement,
  cloneElement,
  PropTypes,
} from 'rax';
import View from 'nuke-view';
import { connectStyle } from 'nuke-theme-provider';

import stylesProvider from '../styles';

class ButtonGroup extends Component {
  getButtons(styles) {
    const buttons = [];
    const { block, children } = this.props;
    children.forEach((btn, index) => {
      if (isValidElement(btn)) {
        buttons.push(
          cloneElement(btn, {
            style: Object.assign(
              {},
              btn.props.style,
              block ? styles['group-block-button'] : styles['group-button'],
              index + 1 === children.length ? styles['group-button-last'] : {}
            ),
          })
        );
      }
    });
    return buttons;
  }
  render() {
    const { block, style = {}, ...others } = this.props;
    const styles = this.props.themeStyle;
    const wrapStyle = Object.assign(
      {},
      styles.group,
      block ? styles['group-block'] : {},
      style
    );
    return (
      <View {...others} style={wrapStyle}>
        {this.getButtons(styles)}
      </View>
    );
  }
}
ButtonGroup.propTypes = {
  rect: PropTypes.bool,
  block: PropTypes.bool,
  fixed: PropTypes.bool,
  style: PropTypes.any,
  children: PropTypes.node,
  themeStyle: PropTypes.object,
};
ButtonGroup.defaultProps = {
  rect: false,
  block: false,
  fixed: false,
  shape: 'normal',
  style: {},
  children: {},
  themeStyle: {},
};
ButtonGroup.contextTypes = {
  parentPath: PropTypes.any,
  parentStyle: PropTypes.any,
  androidConfigs: PropTypes.any,
  commonConfigs: PropTypes.any,
};
ButtonGroup.displayName = 'ButtonGroup';

const StyledButtonGroup = connectStyle(stylesProvider)(ButtonGroup);

export default StyledButtonGroup;
