/**
 * 用户端点。
 */
var express = require('express');
var router = express.Router();
var user = require("../repository/doctor.repo.js");
var http = require('http');

var configFile = require('../include/commons').CONFIG_FILE;
var config = require('../resources/config/' + configFile);
var log = require("../util/log.js");
var objectUtil = require('../util/objectUtil');

var APIv1 = require('../include/endpoints').APIv1;

/**
 * 登录。用户登录后，更新数据库中的在线状态。
 *
 * 请求URL：
 *  /users/login?user_id=sand&token=0PFWlKmLBN9YzhCfFWVgYA&client_id=H6FYbDejks6VjMmW3uH7V6&platform=0
 *
 * 参数说明：
 *  user_id：用户ID
 *  token：个推的token
 *  client_id：个推的client id
 *  platform：平台类型，0为iOS，1为Android
 */
router.get(APIv1.Users.Login, function (req, res) {
    var userId = req.query.user_id;
    var token = req.query.token;
    var clientId = req.query.client_id;
    var platform = req.query.platform;
    if (userId == null) {
        throw {httpStatus: 406, message: 'Missing field "user_id".'};
    }

    if (token == null) {
        throw {httpStatus: 406, message: 'Missing field "token".'};
    }

    if (clientId == null) {
        throw {httpStatus: 406, message: 'Missing field "client_id".'};
    }

    if (platform == null) {
        throw {httpStatus: 406, message: 'Missing field "platform".'};
    }

    user.deleteToken(token, function (err, result) {
        if (err) {
            log.error('Error occurs when user login and delete token: ', err);

            res.status(500).send({message: 'Error occurs when user login and delete token.'});
        } else {
            user.login(userId,
                token,
                clientId,
                platform,
                function (err, result) {
                    if (err) {
                        log.error('Error occurs when user login and delete token: ', err);

                        res.status(500).send({message: 'Error occurs when user login.'})
                        return;
                    }

                    res.status(200).end();
                });
        }
    });
});

/**
 * 退出。
 *
 * 请求URL：
 *  /users/logout?user_id=sand
 *
 * 参数：
 *  user_id：用户ID
 */
router.get(APIv1.Users.Logout, function (req, res) {
    if (req.query.user_id == null) {
        throw {httpStatus: 406, message: 'Logout Failed. Missing field: user_id.'};
    }

    user.logout(req.query.user_id,
        function (err, result) {
            if (err) {
                log.error("Logout failed: ", err);

                res.status(416).send({message: 'Logout failed.'});
            }

            res.status(200).end();
        });
});

/**
 * 更新客户端状态。
 *
 * 请求URL：
 *  /users/:user_id/status
 *
 * POST参数格式:
 *  {status: 1}, app状态，0在后台，1在前台
 */
router.post(APIv1.Users.UserStatus, function (req, res) {
    var userId = req.param('user_id');
    var status = req.body;
    if (!objectUtil.isJsonObject(status)) {
        throw {httpStatus: 406, message: "Problems parsing json."};
    }

    if (userId === null || (status.status != 0 && status.status != 1)) {
        throw {httpStatus: 406, message: 'Validation Failed. Missing fields.'};
    }

    user.updateStatus(userId, status.status,
        function (err, result) {
            if (err) {
                log.error("Update user status failed: ", err.message);

                res.status(500).send({message: 'Update users status failed.'});
            }

            res.status(200).end();
        });
});

module.exports = router;
