/**
 * Copyright 2016 the WHATAP project authors. All rights reserved.
 * Use of this source code is governed by a license that
 * can be found in the LICENSE file.
 */

const WHATAP_R = "WHATAP";

var conf        = require('../conf/configure'),
    HashUtil    = require('./hashutil'),
    Hexa32      = require('./hexa32'),
    KeyGen      = require('./keygen'),
    Long        = require('long'),
    Logger      = require('../logger');

var getUserId = function (req, res, defValue) {
    try {
        if (conf.user_header_ticket_enabled === true) {
            var ticket = req.headers[conf.user_header_ticket];
            if (ticket != null && ticket.length > 0) {
                return Long.fromNumber(HashUtil.hash(ticket));
            }
        }
        var cookie = req.headers.cookie;
        if (cookie != null) {
            if (cookie.length >= conf.trace_user_cookie_limit) {
                return defValue;
            }
            var x1 = cookie.indexOf(WHATAP_R);
            if (x1 >= 0) {
                var value = '';
                var x2 = cookie.indexOf(';', x1);
                if (x2 > 0) {
                    value = cookie.substring(x1 + WHATAP_R.length + 1, x2);
                } else {
                    value = cookie.substring(x1 + WHATAP_R.length + 1);
                }
                try {
                    return Hexa32.toLong32(value);
                } catch (th) {
                }
            }
        }
        var expires= new Date(Date.now() + (86409000*365*5)).toUTCString();
        var cookie_str = WHATAP_R + "=" + Hexa32.toString32(KeyGen.next()) + "; expires=" + expires +"; path=/";
        res.setHeader("Set-Cookie", cookie_str);
    } catch (e) {
        Logger.printError('WHATAP-193', 'UserIdUtil Error', e);
    }
    return Long.ZERO;
};

var UserIdUtil = {
    getUserId : getUserId
};

module.exports = UserIdUtil;
