errors = require('../errors')
log = require('../log')
config = require('../config')
util = require('../util')
PERMISSIONS = require('../permissions').permissions

UserService = require('../service/UserService')

# session信息中可以给前端的部分
sessionForFrontend = (session)->
    if session
        {id: session._id, idName: session.idName, username: session.username, permissions: session.permissions}
    else
        null

# 用户变员工
exports.gAddStaff = ->
    req = this.request.body
    return this.status = 400 unless req.userId and req.truename
    yield from UserService.gAddStaff(req.userId, req.truename, this.state.userId)
    this.status = 204

exports.gGetUserByContact = ->
    phoneOrEmail = this.query?.phoneOrEmail
    return this.status = 400 unless phoneOrEmail

    user = yield from UserService.gGetUserByContact(phoneOrEmail)
    if user
        this.body = user
    else
        this.stauts = 404

exports.toSignIn = (next)->
    this.render 'sign-in', {myHost: config.myHost}
    yield next

# 登录
exports.gSignIn = ()->
    req = this.request.body
    staffRequired = if this.query?.staff == 'true' then true else false

    throw new errors.UserError('UsernamePasswordRequired') unless req.username and req.password

    session = yield from UserService.gSignIn(req.username, req.password, staffRequired)
    s = sessionForFrontend(session) || {}
    this.body = s

    this.cookies.set('user_id', session._id, {signed: true, httpOnly: true})
    this.cookies.set('user_token', session.token, {signed: true, httpOnly: true})

# 登出
exports.gSignOut = ->
    userId = this.state.userId
    yield from UserService.gSignOut(userId)

    this.cookies.set('user_id', null, {signed: true, httpOnly: true})
    this.cookies.set('user_token', null, {signed: true, httpOnly: true})
    this.status = 204

exports.gPing = (next)->
    session = yield from UserService.gGetOrLoadSession this.state.userId
    this.body = sessionForFrontend session
    yield next

exports.pAccountChanged = (next)->
    req = this.request.body
    return this.status = 401 unless req.appId == config.accountAppId and req.appKey == config.accountAppKey

    ids = req?.accountIds
    UserService.clearAccountCache ids if ids and ids.length

    this.status = 204

    yield next

exports.gListStaff = ->
    staffs = UserService.listStaff()
    this.body = {staffs, permissions: PERMISSIONS}
    yield return

exports.gUpdatePermissions = ->
    staffId = this.params.id
    applied = this.request.body
    yield from UserService.gUpdatePermissions staffId, applied
    this.status = 204