/**
 * SignSignout view
 *
 * Generated by coz on 10/9/2016,
 * from a template provided by apeman-asset-templates.
 *
 * @function SignSignoutView
 */
'use strict'

import React, { Component, PropTypes as types } from 'react'
import defineDebug from 'debug'
import { ApView, ApViewHeader, ApViewBody, ApViewFooter } from 'apeman-react-basic'
import {
  asView,
  asConnected,
  asLocaled,
  asServed,
  forSpin,
  combine
} from '../../wrappers'

import { SessionFields } from 'ore-fol-enums'

const { SIGNED_SESSION } = SessionFields
const debug = defineDebug('project:view:sign-signout')

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

  static get defaultProps () {
    return {}
  }

  render () {
    const s = this
    const {
      props,
      l
    } = s
    return (
      <ApView id='sign-signout-view'
              className='view'
              way={ props.way }
              spinning={ props.spinning }
      >
        <ApViewHeader onLeftTap={ s.handlePop }
                      leftText={ null }
                      leftIcon={ null }
                      titleText={ null }
                      titleIcon={ null }
                      onRightTap={ null }
                      rightIcon={ null }
        />

        <ApViewBody>
          <p>{ l('alt.SIGNOUT') }</p>
        </ApViewBody>
      </ApView>
    )
  }

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

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

  componentDidMount () {
    debug('didMount')
    const s = this
    const { props } = s
    let { signed } = props
    if (signed) {
      s.handleSignout()
    } else {
      s.handlePop()
    }
  }

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

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

  handleSignout () {
    const s = this
    const { l } = s
    const { use } = s.service('apiService')
    const { infoToast } = s.service('toastService')
    const { delSession } = s.service('sessionService')
    return s.applySpinWhile(() =>
      use('signApi').then((signApi) =>
        signApi.signout().then(() => {
          delSession(SIGNED_SESSION)
          infoToast(l('toasts.SIGNOUT_SUCCESS'))
          s.handlePopAll()
        }))
    )
  }
}

export default combine(
  asServed(), forSpin(),
  asLocaled(), asView(),
  asConnected()
)(SignSignoutView)

