/*
* @Author: zhouningyi
* @Date: 2016-12-27 15:52:11
*/

import React, { Component, PropTypes } from 'react';
import UiBase from './../uiBase';
import { ChromePicker } from 'react-color';

const defaultStyle = {
  color: '#f00'
};

export default class Color extends UiBase {
  static propTypes = {
    data:    PropTypes.any.isRequired,
    onChange: PropTypes.func.isRequired,
    onFinishChange: PropTypes.func,
    colorType: PropTypes.string,
  }
  constructor(props: any) {
    super(props);
    this.state = {
      displayColorPicker: false,
      color: defaultStyle.color
    };
  }
  handleClick = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker })
  }
  handleClose = () => {
    this.setState({ displayColorPicker: false })
  }
  _getColor(c){
    const colorType = this.props.colorType || 'rgba';
    if(colorType.indexOf('rgb') !== -1) {
      const rgb = c.rgb;
      return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${rgb.a})`;
    } else if (colorType.indexOf('hsl') !== -1){
      const hsl = c.hsl;
      const s = Math.floor(hsl.s * 100) + '%';
      const l = Math.floor(hsl.l * 100) + '%';
      return `hsla(${hsl.h}, ${s}, ${l}, ${hsl.a})`;
    } else if (colorType === 'hex') {
      return c.hex;
    }
    return c.hex;
  }
  handleChange = (c) => {
    const color = this._getColor(c);
    const data = Object.assign(this.state.data, {
      value: color
    });
    this.setState({
      data: data
    });
    this.onChange(color);
  }

  onChange = (value) => {
    const d = this._getDataObject(value);
    (this.props.onChange || empty)(d);
  }
  _getColorPicker = () => {
    const state = this.state;
    const bol = state.displayColorPicker;
    if(bol) return (
       <div className="z_color-popover">
         <div className="z_color-cover" onClick={ this.handleClose }/>
         <ChromePicker color={ state.data.value } onChange={ this.handleChange } />
       </div>
    );
    return null;
  }

  _genUI() {
    const {value} = this.state.data;
    const {heightPhi} = this.props;
    const height = this._getDefaultHeight() * heightPhi + 'px';
    return (
      <div className="z_color-picker" style={this._getSelectorStyle()}>
        <div className="z_color-swatch z_color-transparent-image" style={{height}} onClick={ this.handleClick }>
          <div className="z_color-shower" style={ {backgroundColor: value} } />
        </div>
        { this._getColorPicker() }
      </div>
    );
  }
};

