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

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

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

const { CLOSE_ICON, SIGNIN_ICON } = IconClasses
const { SIGNED_SESSION } = SessionFields
const { REMEMBER_SIGN } = PreferenceFields
const { frontendLogo } = AssetSetting
const debug = defineDebug('project:view:sign-signin')

/** @lends SignSigninView */
class SignSigninView extends Component {
  // --------------------
  // Specs
  // --------------------
  static get propTypes () {
    return {
      /** Hide social login buttons */
      hideSocial: types.bool
    }
  }

  static get defaultProps () {
    return {
      hideSocial: false
    }
  }

  render () {
    const s = this
    const {
      props,
      labels,
      errors,
      l
    } = s
    return (
      <ApView id='sign-signin-view'
              className='view'
              spinning={ props.spinning }
              way={ props.way }
      >
        <ApViewHeader onLeftTap={ s.handlePop }
                      leftText={ null }
                      leftIcon={ CLOSE_ICON }
                      titleText={ l('titles.SIGNIN') }
                      titleIcon={ SIGNIN_ICON }
                      onRightTap={ null }
                      rightIcon={ null }
        />
        <ApViewBody>
          {
            props.message ? (
                <div className='signin-message'>{ props.message }</div>
              ) : (
                <div className='signin-logo'>
                  <img src={ '/' + frontendLogo } alt='' className='signin-logo-icon'/>
                  <span className='signin-logo-text'>{ l('app.APP_NAME_SHORT') }</span>
                </div>
              )
          }
          <SigninForm values={ props.entryValues }
                      onUpdate={ s.handleEntryUpdate }
                      labels={ labels }
                      errors={ errors }
                      onSubmit={ s.handleSubmit }
                      onSocial={ s.handleSocial }
                      onSignup={ s.handleSignup }
                      onRecover={ s.handleRecover }
                      rememberEnabled={ props.rememberEntry }
                      actions={{ toggleRemember: s.handleRemember }}
                      hideSocial={ props.hideSocial }
          />
        </ApViewBody>
      </ApView>
    )
  }

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

  componentDidMount () {
    debug('didMount')
    const s = this
    const location = get('location')
    s.handleEntryUpdate({
      host: location.host
    })
  }

  // --------------------
  // Dynamic variables
  // --------------------
  get labels () {
    const s = this
    const { l } = s
    return {
      key: l('labels.SIGN_KEY'),
      password: l('labels.PASSWORD'),
      submit: l('buttons.DO_SIGNIN'),
      signup: l('links.SIGNUP'),
      remember: l('checkbox.REMEMBER_SIGN'),
      recover: l('links.RECOVER'),
      twitter: l('buttons.DO_SIGNIN_TWITTER'),
      google: l('buttons.DO_SIGNIN_GOOGLE'),
      facebook: l('buttons.DO_SIGNIN_FACEBOOK')
    }
  }

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

  // --------------------
  // Handlers
  // --------------------
  handleSignup () {
    const s = this
    return s.handlePushToModal('SignSignup')
  }

  handleRecover () {
    const s = this
    return s.handlePushToModal('RecoverSend')
  }

  handleRemember (rememberEntry) {
    const s = this
    const { setPreference } = s.service('preferenceService')
    setPreference(REMEMBER_SIGN, rememberEntry)
  }

  handleSubmit () {
    const s = this
    const {
      props, l
    } = s
    const { infoToast } = s.service('toastService')
    const { setSession } = s.service('sessionService')
    const { use } = s.service('apiService')
    let { rememberEntry } = props
    return s.applySpinWhile(() =>
      use('signApi').then((signApi) =>
        signApi.signin(props.entryValues)
          .then(() => {
            signApi.signget().then((signed) =>
              setSession(SIGNED_SESSION, signed)
            )
          })
          .then(() => {
            infoToast(l('toasts.SIGNIN_SUCCESS'))
            s.handlePop().then(() => {
              if (rememberEntry) {

              } else {
                s.handleEntryClear()
              }
            })
          })
          .catch(s.handleEntryErrorCatch)
      )
    )
  }

  handleSocial (provider) {
    const location = get('location')
    let { protocol, hostname, port } = location
    switch (provider) {
      case 'twitter':
        if (hostname === 'localhost') {
          hostname = '127.0.0.1'
        }
        break
      default:
        break
    }
    let host = port && Number(port) !== 80 ? [ hostname, port ].join(':') : hostname
    location.href = `${protocol}//${host}/oauth/${provider}`
  }

}

export default combine(
  forEntry(),
  asServed(), forSpin(),
  asLocaled(), asView(),
  asConnected(
    (state, { srvc }) => {
      const { getPreference } = srvc.preferenceService
      return {
        rememberEntry: getPreference(REMEMBER_SIGN)
      }
    }
  )
)(SignSigninView)
