import { getCookie, setCookie, deleteCookie } from "./utility/cookie";
import { init, r, lang } from "./utility/lgres";
import { get, post, upload } from "./utility/request";
import { nullOrEmpty, contains, endsWith, padStart, formatUrl, escapeHtml, escapeEmoji } from "./utility/strings";

let g = typeof globalThis !== 'undefined' ? globalThis : self;

function isPositive(n) {
    return !isNaN(n) && n > 0;
}

function isMobile() {
    return /mobile/i.test(navigator.userAgent);
}

function throttle(method, delay = 100, context = g, ...args) {
    if (method == null) {
        return;
    }
    method.tiid && clearTimeout(method.tiid);
    const current = new Date();
    if (method.tdate == null || current - method.tdate > delay) {
        method.apply(context, args);
        method.tdate = current;
    } else {
        method.tiid = setTimeout(() => method.apply(context, args), delay);
    }
}

function debounce(method, delay = 100, context = g, ...args) {
    if (method == null) {
        return;
    }
    method.tiid && clearTimeout(method.tiid);
    method.tiid = setTimeout(() => method.apply(context, args), delay);
}

function truncate(v) {
    return (v > 0 ? Math.floor : Math.ceil)(v);
}

function isEmail(text) {
    return /^\w[-\w.+]*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(text);
}

function isPhone(text) {
    if (/^[1-9]\d{9,}$/.test(text)) {
        return true;
    }
    if (/^\+?[1-9][\d-]{9,}\d$/.test(text) && /^[1-9]\d{9,}$/.test(text.replace('+', '').replace(new RegExp('-', 'g'), ''))) {
        return true;
    }
    return false;
}

export {
    // cookie
    getCookie,
    setCookie,
    deleteCookie,
    // lgres
    init,
    r,
    lang,
    // request
    get,
    post,
    upload,
    // strings
    nullOrEmpty,
    contains,
    endsWith,
    padStart,
    formatUrl,
    escapeHtml,
    escapeEmoji,
    // variables
    g as global,
    isPositive,
    isMobile,
    // functions
    throttle,
    debounce,
    truncate,
    isEmail,
    isPhone
}