/**
 * apeman react package for password component.
 * @class ApPassword
 */

'use strict'

import React, {PropTypes as types} from 'react'
import ReactDOM from 'react-dom'
import classnames from 'classnames'
import {ApIcon} from 'apeman-react-icon'

const DEFAULT_SHOW_ICON = 'ion ion-eye'
const DEFAULT_HIDE_ICON = 'ion ion-eye-disabled'

/** @lends ApPassword */
const ApPassword = React.createClass({

  // --------------------
  // Specs
  // --------------------

  propTypes: {
    /** Name of text input */
    name: types.string,
    /** Value of password input */
    value: types.string,
    /** Placeholder of password input */
    placeholder: types.string,
    /** Icon class for show button */
    showIcon: types.string,
    /** Icon class for hide icon */
    hideIcon: types.string
  },

  statics: {
    DEFAULT_SHOW_ICON,
    DEFAULT_HIDE_ICON
  },

  getInitialState () {
    return {
      visible: false
    }
  },

  getDefaultProps () {
    return {
      name: '',
      value: '',
      placeholder: '',
      showIcon: DEFAULT_SHOW_ICON,
      hideIcon: DEFAULT_HIDE_ICON
    }
  },

  render () {
    const s = this
    let { props, state } = s
    let hasVal = !!props.value
    let type = state.visible ? 'text' : 'password'
    let icon = state.visible ? props.hideIcon : props.showIcon
    let className = classnames('ap-password-wrap', {
      'ap-password-wrap-empty': !hasVal
    })
    return (
      <span className={ className }>
        <input id={ props.id }
               name={ props.name }
               placeholder={ props.placeholder }
               onChange={ props.onChange }
               className={ classnames('ap-password', props.className) }
               ref={ (input) => { s.input = input } }
               value={ props.value }
               type={ type }/>
        <a className='ap-password-toggle-button' onClick={ s.handleToggleTap }>
            <span className='ap-password-toggle-aligner'>&nbsp;</span>
            <ApIcon className={ classnames('ap-password-toggle-icon', icon) }/>
        </a>
      </span>
    )
  },

  // --------------------
  // Custom
  // --------------------

  handleToggleTap (e) {
    const s = this
    let { state }  = s
    s.setState({
      visible: !state.visible
    })
    ReactDOM.findDOMNode(s.input).focus()
  }
})

export default ApPassword
