/**
 * SignSignup view
 *
 * Generated by coz on 8/16/2016,
 * from a template provided by apeman-asset-templates.
 *
 * @function SignSignupView
 */
'use strict'

import React, { Component, PropTypes as types } from 'react'
import defineDebug from 'debug'
import { SignupForm } from '../../fragments'
import { ApView, ApViewHeader, ApViewBody } from 'apeman-react-basic'
import { IconClasses, SessionFields } from 'ore-fol-enums'

import {
  asView,
  asConnected,
  asLocaled,
  forEntry,
  asServed,
  forSpin,
  combine
} from '../../wrappers'
import { get } from 'bwindow'

const { SIGNUP_ICON, CLOSE_ICON } = IconClasses
const { SIGNED_SESSION, CAPTCHA_SESSION } = SessionFields

const debug = defineDebug('project:view:sign-signup')

/** @lends SignSignupView */
class SignSignupView extends Component {
  // --------------------
  // Specs
  // --------------------
  static get propTypes () {
    return {}
  }

  static get defaultProps () {
    return {}
  }

  render () {
    const s = this
    const {
      props,
      errors,
      placeholders,
      labels,
      l
    } = s

    return (
      <ApView id='sign-signup-view'
              className='view'
              spinning={ props.spinning }
              way={ props.way }
      >
        { props.dialog }
        <ApViewHeader onLeftTap={ s.handlePop }
                      leftText={ null }
                      leftIcon={ CLOSE_ICON }
                      titleText={ l('titles.SIGNUP') }
                      titleIcon={ SIGNUP_ICON }
                      onRightTap={ null }
                      rightIcon={ null }
        />
        <ApViewBody>
          <SignupForm spinning={ props.spinning }
                      values={ props.entryValues }
                      onUpdate={ s.handleEntryUpdate }
                      placeholders={ placeholders }
                      labels={ labels }
                      errors={ errors }
                      onSubmit={ s.handleSubmit }
                      captchaImage={ props.captchaImage }
                      captchaSpinning={ props.captchaSpinning }
                      actions={ { captchaRefresh: s.handleCaptchaRefresh } }
          />
        </ApViewBody>
      </ApView>
    )
  }

  // --------------------
  // Lifecycle
  // --------------------

  componentWillMount () {
    debug('willMount')
    const s = this
  }

  componentDidMount () {
    debug('didMount')
    const s = this
    let { handleCaptchaRefresh } = s
    handleCaptchaRefresh()

    const location = get('location')
    s.handleEntryUpdate({
      host: location.host
    })
  }

  componentWillUnmount () {
    debug('willUnmount')
    const s = this
  }

  // --------------------
  // Dynamic Variables
  // --------------------

  get labels () {
    const s = this
    const { l } = s
    return {
      key: l('labels.USER_KEY'),
      email: l('labels.EMAIL'),
      password: l('labels.PASSWORD'),
      captcha: l('labels.CAPTCHA'),
      captchaRefresh: l('buttons.DO_REFRESH'),
      submit: l('buttons.DO_SIGNUP'),
      term: l('links.TERMS')
    }
  }

  get placeholders () {
    const s = this
    const { l } = s
    return {
      captcha: l('placeholders.CAPTCHA')
    }
  }

  get errors () {
    const s = this
    const { localizeErrors } = s.service('localeService')
    const { props, labels } = s
    return localizeErrors(props.entryErrors, { labels })
  }

  // --------------------
  // Handlers
  // --------------------

  handleSubmit () {
    const s = this
    const { use } = s.service('apiService')
    const { infoToast, errorToast } = s.service('toastService')
    const { setSession } = s.service('sessionService')
    const { props, l } = s
    let { entryValues } = props
    if (!entryValues.agreeChecked) {
      errorToast(l('toasts.NEEDS_AGREE_CHECK'))
      return
    }
    return s.applySpinWhile(() =>
      use('signApi').then((signApi) =>
        signApi.signup(entryValues)
          .then(() => {
            signApi.signget().then((signed) =>
              setSession(SIGNED_SESSION, signed)
            )
          })
          .then(() => {
            infoToast(l('toasts.SIGNUP_SUCCESS'))
            s.handlePop().then(s.handleEntryClear)
          })
          .catch(s.handleEntryErrorCatch)
      )
    )
  }

  handleCaptchaRefresh () {
    const s = this
    const { use } = s.service('apiService')
    const { setSession } = s.service('sessionService')
    return s.applySpinWhile({
      captchaSpinning: () =>
        use('captchaApi').then((captchaApi) =>
          captchaApi.issue().then(({ src }) =>
            setSession(CAPTCHA_SESSION, { src })
          ).then(() =>
            s.handleEntryUpdate({ 'captcha': '' })
          )
        )
    })
  }
}

export default combine(
  forEntry(),
  asServed(),
  forSpin(),
  asLocaled(),
  asView(),
  asConnected((state, { srvc }) => {
    const { getSession } = srvc.sessionService
    return {
      captchaImage: (getSession(CAPTCHA_SESSION) || {}).src
    }
  })
)(SignSignupView)
