import React, { PureComponent, PropTypes } from 'react';
import './setDisplayName.scss'

class SetDisplayName extends React.Component {

  static defaultProps = {
    func: () => {},
    msgBarActions: () => {},
  }
  constructor(props){
    super()
    this.state = {
      shouldEdit: false,
      displayNameInner: props.displayName,
    }
    this.displayName=props.displayName||''

  }


  // componentDidMount() {
  //   this.setState({ displayNameInner: this.props.displayName });
  // }
 

  componentWillReceiveProps(nextProps) {
    if (nextProps.displayName !== this.props.displayName) {
      this.setState({
        displayNameInner: nextProps.displayName,
      });
    }
  }

 

  setDisplayName = (e) => {
    if (e.target.value.length > 20) {
      this.props.displayRule && window.pay.dispatch({ type: 'msgbar.show', data: { message:this.props.displayRule, timeout: 3000 } })
    } else {
      this.setState({ displayNameInner: e.target.value });
    }
  }

  updateDisplayName = (e) => {
    this.setState({shouldEdit:false})
    if (e.target.value.length > 20) {
      this.props.displayRule && window.pay.dispatch({ type: 'msgbar.show', data: { message:this.props.displayRule, timeout: 3000 } })
    } else if( this.displayName!==this.state.displayNameInner && this.state.displayNameInner!==null){
      this.props.updateDisplayName(this.state.displayNameInner)
      this.displayName=this.state.displayNameInner
    }
  }

  renderEdit = () => {
    if (this.state.shouldEdit) {
      return (
        <input className="setDisplay_input"
          value={this.state.displayNameInner || ''}
          autoFocus
          onChange={this.setDisplayName}
          onBlur={this.updateDisplayName}
        />
      );
    }
  }

  render() {
    return (
      <div style={{ lineHeight: '16px',display:'flex',minWidth:143}} className="setDisplayStyle">
        { this.renderEdit() }
        { !this.state.shouldEdit && this.state.displayNameInner }
        <span 
          className="fa fa-pencil-square-o setDisplay_IconShow"
          onClick={()=>{
            this.setState({shouldEdit:true})
          }}
         >
         </span>
      </div>
    );
  }
}

export default SetDisplayName;
