var Cookie = require("cookie");

var loggedIn = false;
var isLoggedIn = function () {
    if (!loggedIn) {
        loggedIn = Cookie.get("username") && Cookie.get("password") && Cookie.get("osinfo");
    }
    return loggedIn;
};

function _isEmptyStr(t) {
    return String.prototype.trim ? "" === t.trim() : "" === t.replace(/^\s+/, "").replace(/\s+$/, "")
}

function _udb_decorateURL(t) {
    if (_isEmptyStr(t)) {
        t = top.location.href;
        var e = t.indexOf("#");
        return -1 != e && (t = t.substring(0, e)), t
    }
    if (t.startsWith("http")) return t;
    var o = "http://";
    return top.location.href.startsWith("https") && (o = "https://"), o + document.domain + t
}


function ensureUDBSDK(callback) {
    if (window.dwUDBProxy) {
        callback(window.dwUDBProxy);
    } else {
        $.getScript("http://assets.dwstatic.com/common/js/dwudbproxy.js", function () {
            setTimeout(function () {
                callback(window.dwUDBProxy);
            }, 500);
        });
    }
}

var login = function (callbackURL) {
    ensureUDBSDK(function (dwUDBProxy) {
        try {
            dwUDBProxy.login(callbackURL || "");
        } catch (ex) {}
    });
};

var logout = function (callbackURL) {
    ensureUDBSDK(function (dwUDBProxy) {
        try {
            dwUDBProxy.logout(callbackURL || "");
        } catch (ex) {}
    });
};

var isAdmin = null;
var REG_ADMIN = /^dw_[a-z]+/;
var isAdmin = function () {
    if (isAdmin == null && isLoggedIn()) {
        isAdmin = REG_ADMIN.test(Cookie.get("username") || "");
    }
    return isAdmin || false;
};

var parseDate = function (timeStr) {
    return new Date(parseInt(timeStr, 10) * 1000);
};

var getFriendlyDateStr = function (date) {
    var timeSpan = new Date().getTime() - date.getTime();

    var ONE_MINUTE = 60 * 1000,
        ONE_HOUR = 60 * ONE_MINUTE,
        ONE_DAY = 24 * ONE_HOUR,
        ONE_MONTH = 30 * ONE_DAY,
        ONE_YEAR = 12 * ONE_MONTH;

    var friendlyString = '';

    if (timeSpan < ONE_MINUTE) {
        friendlyString = "刚刚";
    } else if (timeSpan < ONE_HOUR) {
        friendlyString = Math.floor(timeSpan / ONE_MINUTE) + "分钟前";
    } else if (timeSpan < ONE_DAY) {
        friendlyString = Math.floor(timeSpan / ONE_HOUR) + "小时前";
    } else if (timeSpan < ONE_MONTH) {
        friendlyString = Math.floor(timeSpan / ONE_DAY) + "天前";
    } else if (timeSpan < ONE_YEAR) {
        friendlyString = Math.floor(timeSpan / ONE_MONTH) + "个月前";
    } else if (timeSpan >= ONE_YEAR) {
        friendlyString = Math.floor(timeSpan / ONE_YEAR) + "年前";
    }

    return friendlyString;
};

var getDateTomorrow = function () {
    var d = new Date();
    d.setHours(0, 0, 0, 0);
    return new Date(d.getTime() + 24 * 60 * 60 * 1000);
};

/**用户个人页 */
var getUserLink = function (uid) {
    return uid && uid != "0" ? "http://bbs.duowan.com/space-uid-" + uid + ".html" : "#";
};

var jqWindow = $(window);

var scrollIntoView = function (el) {
    var jqEl = $(el);
    if (!jqEl.is(':visible')) {
        return;
    }

    var offsetY = 36;

    var top = jqEl.offset().top;
    var scrollTop = jqWindow.scrollTop();
    var scrollTo;
    if (scrollTop + offsetY > top) {
        scrollTo = top - offsetY;
    }

    if (scrollTo != null) {
        jqWindow.scrollTop(scrollTo);
    }
};

var isInView = function (jqEl) {
    var DELTA = 36;

    var jqOffsetParent = jqEl.offsetParent();
    var offsetParentScrollTop = jqOffsetParent.scrollTop() || 0;

    return jqEl.offset().top < jqWindow.scrollTop() + jqWindow.innerHeight() + (offsetParentScrollTop ? offsetParentScrollTop : offsetParentScrollTop + DELTA);
};

var lazyLoad = function (jqEl, load) {
    var loaded = false;
    var jqOffsetParent = jqEl.offsetParent();

    function check() {
        if (loaded) {
            return;
        }
        // 盒子内嵌页滚动条不在window上；
        if (isInView(jqEl)) {
            jqWindow.off("scroll resize", check);
            jqOffsetParent.off("scroll", check);
            loaded = true;
            load(jqEl);
        }
    }

    jqWindow.on("scroll resize", check);
    jqOffsetParent.on("scroll", check);
    check();
};

function getParam(name) {
    var getParam2 = function (name, str) {
        //获取参数name的值
        var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");

        //再获取?后面的参数
        r = str.match(reg);
        if (r != null) {
            try {
                return decodeURIComponent(r[2]);
            } catch (e) {
                console.log(e + "r[2]:" + r[2]);
                return null;
            }
        }
        return null;
    }

    //先获取#后面的参数
    var str = document.location.hash.substr(2);
    var value = getParam2(name, str);
    if (value == null) {
        str = document.location.search.substr(1);
        value = getParam2(name, str);
    }

    return value;
};

function secondToTime(second) {
    var add0 = (num) => {
        return num < 10 ? '0' + num : '' + num;
    };
    var min = parseInt(second / 60);
    var sec = parseInt(second - min * 60);
    return add0(min) + ':' + add0(sec);
}

function browserVersion() {
    var BROWSER = {};
    var types = {'ie':'msie','firefox':'','chrome':'','opera':'','safari':'','mozilla':'','webkit':'','maxthon':'','qq':'qqbrowser'};
    var USERAGENT = navigator.userAgent.toLowerCase();
	var other = 1;
	for(i in types) {
		var v = types[i] ? types[i] : i;
		if(USERAGENT.indexOf(v) != -1) {
			var re = new RegExp(v + '(\\/|\\s)([\\d\\.]+)', 'ig');
			var matches = re.exec(USERAGENT);
			var ver = matches != null ? matches[2] : 0;
			other = ver !== 0 && v != 'mozilla' ? 0 : other;
		}else {
			var ver = 0;
		}
		eval('BROWSER.' + i + '= ver');
	}
	BROWSER.other = other;
}

module.exports.isLoggedIn = isLoggedIn;
module.exports.login = login;
module.exports.logout = logout;
module.exports.isAdmin = isAdmin;
module.exports.parseDate = parseDate;
module.exports.getFriendlyDateStr = getFriendlyDateStr;
module.exports.getDateTomorrow = getDateTomorrow;
module.exports.getUserLink = getUserLink;
module.exports.scrollIntoView = scrollIntoView;
module.exports.isInView = isInView;
module.exports.lazyLoad = lazyLoad;
module.exports.getParam = getParam;
module.exports.secondToTime = secondToTime;
module.exports.browserVersion = browserVersion;