"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Auth = exports.AuthModuleInit = exports.AuthContext = void 0;
exports.AuthReducer = AuthReducer;
var tslib_1 = require("tslib");
require("./auth.scss");
var react_1 = tslib_1.__importStar(require("react"));
var login_1 = require("../../utility/login");
var v_eris_1 = require("v-eris");
var notifications_1 = require("../Notifications/notifications");
var react_router_dom_1 = require("react-router-dom");
function AuthReducer(state, _a) {
    var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
    var type = _a[0], data = _a[1];
    if (type == "tab") {
        var type_1 = v_eris_1.Common.uint(data.type);
        var errors = tslib_1.__assign({}, state.errors);
        if (type_1 != state.type) {
            errors["name"] = state.name ? (login_1.Login.checkLogin(state.name) || {}).description : "";
            errors["email"] = state.email ? (login_1.Login.checkEmail(state.email) || {}).description : "";
            errors["oldPassword"] = state.oldPassword ? (login_1.Login.checkPass(state.oldPassword, state.policyList[0]) || {}) : "";
            errors["password"] = state.password ? (login_1.Login.checkPass(state.password, state.policyList[0]) || {}) : "";
            errors["password2"] = state.password2 ? (login_1.Login.checkPass(state.password2, state.policyList[0]) || {}) : "";
            errors["server"] = "";
        }
        ;
        return tslib_1.__assign(tslib_1.__assign({}, state), { type: type_1, errors: errors });
    }
    else if (type == "access") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_b = {}, _b["access"] = data.value || 0, _b));
    }
    else if (type == "name") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_c = {}, _c[type] = data.value, _c["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_d = {}, _d["login"] = (login_1.Login.checkLogin(data.value) || {}).description, _d)), _c));
    }
    else if (type == "email") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_e = {}, _e[type] = data.value, _e["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_f = {}, _f["email"] = (login_1.Login.checkEmail(data.value) || {}).description, _f)), _e));
    }
    else if (type == "configuration") {
        return tslib_1.__assign(tslib_1.__assign({}, state), { configuration: data.value });
    }
    else if (type == "password") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_g = {}, _g[type] = data.value, _g["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_h = {}, _h["password"] = (login_1.Login.checkPass(data.value, state.policyList[0]) || ""), _h)), _g));
    }
    else if (type == "oldPassword") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_j = {}, _j[type] = data.value, _j["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_k = {}, _k["oldPassword"] = (login_1.Login.checkPass(data.value, state.policyList[0]) || ""), _k)), _j));
    }
    else if (type == "password2") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_l = {}, _l[type] = data.value, _l["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_m = {}, _m["password2"] = (login_1.Login.checkPass(data.value, state.policyList[0]) || ""), _m)), _l));
    }
    else if (type == "match") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_o = {}, _o["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_p = {}, _p["password2"] = (login_1.Login.checkPassMatch(state.password, state.password2) || {}).description, _p)), _o));
    }
    else if (type == "init") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_q = {}, _q["access"] = data.access || 0, _q["configurationsList"] = data.configurations, _q["policyList"] = data.policy, _q["configuration"] = data.configuration, _q["configurationName"] = data.configurationName, _q["role"] = data.role, _q["roleName"] = data.roleName, _q["passwordAlert"] = data.passwordAlert, _q["passwordNotify"] = data.passwordNotify, _q));
    }
    else if (type == "data") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_r = {}, _r["access"] = data.access || 0, _r["name"] = data.name, _r["token"] = data.token, _r["role"] = data.role, _r["login"] = data.login, _r["email"] = data.email, _r["configuration"] = data.configuration, _r["policy"] = data.policy, _r["persona"] = data.persona, _r));
    }
    else if (type == "server-error") {
        return tslib_1.__assign(tslib_1.__assign({}, state), (_s = {}, _s["errors"] = tslib_1.__assign(tslib_1.__assign({}, state.errors), (_t = {}, _t["server"] = data.description || "", _t)), _s));
    }
    return state;
}
;
var AuthContextDefault = {
    state: {},
    dispatch: function (args) { },
    persona: true,
    access: 0,
    name: "",
    token: "",
    configuration: "default",
    configurationsList: [],
    configurationName: "default",
    roleName: "",
    policy: "",
    policyList: [],
    role: "",
    login: "",
    email: "",
    relogin: function () { },
    async: {
        login: {},
        changePassword: {},
        register: {},
        init: {},
        logout: {},
    }
};
exports.AuthContext = react_1.default.createContext(AuthContextDefault);
var AuthModuleInit = function () {
    var _a = (0, react_1.useReducer)(AuthReducer, {
        access: 0,
        type: 0,
        token: "",
        role: "",
        loading: false,
        name: "",
        email: "",
        oldPassword: "",
        password: "",
        password2: "",
        configuration: "default",
        configurationsList: [],
        policy: "",
        policyList: [],
        logout: false,
        persona: false,
        configurationName: "",
        roleName: "",
        errors: {
            login: "",
            email: "",
            oldPassword: "",
            password: "",
            password2: "",
            configuration: "",
            server: ""
        }
    }), state = _a[0], dispatch = _a[1];
    var lang = (0, react_1.useContext)(v_eris_1.LangContext);
    var cookies = v_eris_1.Cookie.parse(document.cookie);
    var notifications = (0, react_1.useContext)(notifications_1.NotificationsContext);
    var nav = (0, react_router_dom_1.useNavigate)();
    var data = {};
    try {
        data = JSON.parse(cookies.data);
    }
    catch (e) { }
    ;
    (0, react_1.useEffect)(function () {
        dispatch(["data", {
                access: data.access,
                name: data.name,
                token: data.token,
                role: data.role,
                login: data.login,
                configuration: state.configuration,
                policy: data.policy,
                email: data.email,
                persona: data.persona
            }]);
    }, [data.access, data.name, data.token, data.role]);
    var login = (0, v_eris_1.useAsync)({
        method: "POST",
        url: "./users/login"
    }, {
        login: state.name,
        password: state.password,
        configuration: state.configuration
    });
    var register = (0, v_eris_1.useAsync)({
        method: "POST",
        url: "./users/register"
    }, {
        name: state.name,
        email: state.email,
        login: (state.name || "").toLowerCase(),
        configuration: state.configuration,
        password: state.password,
        password2: state.password2,
    });
    login.onResponse(function (item) {
        dispatch(["access", { value: item.access }]);
        init.fetch();
        nav("/");
    }, function (e) {
        dispatch(["server-error", { description: e.description }]);
        notifications.alert(e.errors);
    });
    register.onResponse(function (item) {
        dispatch(["access", { value: item.access }]);
        init.fetch();
    }, function (e) {
        dispatch(["server-error", { description: e.description }]);
        notifications.alert(e.errors);
    });
    var changePassword = (0, v_eris_1.useAsync)({
        method: "POST",
        url: "./users/changePassword"
    }, {
        oldPassword: state.oldPassword,
        password: state.password,
        password2: state.password2,
    });
    changePassword.onResponse(function (item) {
        init.fetch();
    }, function (e) {
        dispatch(["server-error", { description: e.description }]);
        notifications.alert(e.errors);
    });
    (0, react_1.useEffect)(function () {
        init.fetch();
    }, []);
    var logout = (0, v_eris_1.useAsync)({
        method: "GET",
        url: "./users/logout"
    }, {});
    logout.onResponse(function (response) {
        init.fetch();
        nav("/");
    }, function (e) {
        dispatch(["server-error", { description: e.description }]);
        notifications.alert(e.errors);
    });
    var init = (0, v_eris_1.useAsync)({
        method: "GET",
        url: "./users/init"
    }, {});
    init.onResponse(function (response) {
        for (var key in response.configurations) {
            response.configurations[key].value = response.configurations[key].token;
            response.configurations[key].title = response.configurations[key].name;
        }
        ;
        response.configurations.reverse();
        dispatch(["init", {
                access: response.access,
                configuration: response.configuration,
                configurations: response.configurations,
                configurationName: response.configurationName,
                role: response.role,
                roleName: response.roleName,
                policy: response.policy,
                passwordAlert: response.passwordAlert,
                passwordNotify: response.passwordNotify,
            }]);
        if (response.passwordNotify < 0 && response.passwordAlert > 0 && !data.persona) {
            var day = 24 * 60 * 60;
            var delta = v_eris_1.Common.uint((response.passwordAlert - response.passwordNotify) / day);
            notifications.alert([{ desc: "Password is too old, you have " + delta + " days left to change it" }]);
        }
        ;
    }, function (e) { });
    var relogin = function () {
        if (state.persona) {
            dispatch(["access", { value: 0 }]);
        }
        else {
            logout.fetch();
        }
        ;
    };
    return {
        state: state,
        dispatch: dispatch,
        access: state.access,
        name: state.name,
        token: state.token,
        configuration: state.configuration,
        configurationsList: state.configurationsList,
        configurationName: state.configurationName,
        roleName: state.roleName,
        policy: state.policy,
        policyList: state.policyList,
        role: state.role,
        login: state.login,
        email: state.email,
        persona: state.persona,
        relogin: relogin,
        async: {
            login: login,
            changePassword: changePassword,
            register: register,
            init: init,
            logout: logout
        },
        context: exports.AuthContext
    };
};
exports.AuthModuleInit = AuthModuleInit;
var Auth = function (props) {
    var module = (0, react_1.useContext)(exports.AuthContext);
    var state = module.state, dispatch = module.dispatch, async = module.async;
    var lang = (0, react_1.useContext)(v_eris_1.LangContext);
    var cookies = v_eris_1.Cookie.parse(document.cookie);
    var notifications = (0, react_1.useContext)(notifications_1.NotificationsContext);
    var nav = (0, react_router_dom_1.useNavigate)();
    var data = {};
    try {
        data = JSON.parse(cookies.data);
    }
    catch (e) { }
    ;
    //
    if (state.access >= 3 && (state.passwordAlert >= 0 || data.persona || state.access >= 9)) {
        return (react_1.default.createElement("div", null));
    }
    ;
    var type = state.access >= 0 && (state.passwordAlert < 0 && !data.persona) ? 2 : state.type;
    return (react_1.default.createElement("div", { className: "eris-auth-wrap fullscreen" },
        react_1.default.createElement("div", { className: "eris-auth-sun" }),
        react_1.default.createElement("div", { className: "eris-auth-ground" }),
        react_1.default.createElement("div", null, state.access < 3 && !data.persona ? (react_1.default.createElement("div", { className: "eris-auth-deny" }, lang.get(state.access < 1 ? "Server::Banned" : "Server::NeedConfirmation"))) : (null)),
        react_1.default.createElement("div", { className: "eris-auth" },
            react_1.default.createElement("div", { className: "eris-auth-line" }, type == 2 ? (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement("div", { className: "eris-auth-tab" + (type == 2 ? " eris-auth-tab-selected" : ""), onClick: function () { dispatch(["tab", { "type": 2 }]); } }, lang.get("Auth::PasswordMustChange")))) : (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement("div", { className: "eris-auth-tab" + (type == 0 ? " eris-auth-tab-selected" : ""), onClick: function () { dispatch(["tab", { "type": 0 }]); } }, lang.get("Auth::Login")),
                react_1.default.createElement("div", { className: "eris-auth-tab" + (type == 1 ? " eris-auth-tab-selected" : ""), onClick: function () { dispatch(["tab", { "type": 1 }]); } }, lang.get("Auth::Register"))))),
            react_1.default.createElement("div", { className: "eris-auth-content" },
                type == 2 ? (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement("div", { className: "eris-auth-password" }),
                    react_1.default.createElement("input", { placeholder: lang.get("Auth::OldPassword"), type: "password", onKeyUp: function (e) {
                            if (e.keyCode == 13) {
                                (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                            }
                            else {
                                dispatch(["oldPassword", { value: e.target.value }]);
                            }
                            ;
                        } })))
                    :
                        (react_1.default.createElement(react_1.default.Fragment, null,
                            react_1.default.createElement("span", { className: "eris-auth-configurations" }),
                            react_1.default.createElement("select", { value: state.configuration, onChange: function (e) {
                                    dispatch(["configuration", { value: e.target.value }]);
                                } }, state.configurationsList.map(function (item) {
                                return react_1.default.createElement("option", { value: item.token, key: item.token }, item.name);
                            })),
                            react_1.default.createElement("div", { className: "eris-auth-name" }),
                            react_1.default.createElement("input", { placeholder: lang.get("Auth::Name"), type: "name", onKeyUp: function (e) {
                                    if (e.keyCode == 13) {
                                        (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                                    }
                                    else {
                                        dispatch(["name", { value: e.target.value }]);
                                    }
                                    ;
                                } }),
                            react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.login ? "" : " hidden") }, state.errors.login))),
                type == 1 ?
                    (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "eris-auth-email" }),
                        react_1.default.createElement("input", { placeholder: lang.get("Auth::Email"), type: "email", onKeyUp: function (e) {
                                if (e.keyCode == 13) {
                                    (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                                }
                                else {
                                    dispatch(["email", { value: e.target.value }]);
                                }
                                ;
                            } }),
                        react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.email ? "" : " hidden") }, state.errors.email)))
                    :
                        (null),
                react_1.default.createElement("div", { className: "eris-auth-password" }),
                react_1.default.createElement("input", { placeholder: lang.get("Auth::Password"), type: "password", onKeyUp: function (e) {
                        if (e.keyCode == 13) {
                            (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                        }
                        else {
                            dispatch(["password", { value: e.target.value }]);
                            dispatch(["match"]);
                        }
                        ;
                    } }),
                react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.password ? "" : " hidden") }, Array.isArray(state.errors.password) ?
                    state.errors.password.map(function (error, index) {
                        return react_1.default.createElement("div", { key: index }, error.description);
                    })
                    :
                        state.errors.password),
                type == 1 || type == 2 ?
                    (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "eris-auth-password" }),
                        react_1.default.createElement("input", { placeholder: lang.get("Auth::Confirmation"), type: "password", onKeyUp: function (e) {
                                if (e.keyCode == 13) {
                                    (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                                }
                                else {
                                    dispatch(["password2", { value: e.target.value }]);
                                    dispatch(["match"]);
                                }
                                ;
                            } }),
                        react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.password2 ? "" : " hidden") }, Array.isArray(state.errors.password2) ?
                            state.errors.password2.map(function (error, index) {
                                return react_1.default.createElement("div", { key: index }, error.description);
                            })
                            :
                                state.errors.password2),
                        react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.server ? "" : " hidden") },
                            react_1.default.createElement("div", { className: "eris-auth-notice-error" }, lang.get("Auth::ServerError")),
                            state.errors.server),
                        react_1.default.createElement("div", { className: "eris-auth-button" + (state.loading ? " eris-auth-loading" : ""), onClick: function () {
                                (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                            } }, lang.get(type == 2 ? "Auth::ChangePassword" : "Auth::RegisterNow")),
                        react_1.default.createElement("div", { className: "eris-auth-button" + (state.loading ? " eris-auth-loading" : "") + (type == 2 ? "" : " hidden"), onClick: function () {
                                async.logout.fetch();
                            } }, data.persona ? lang.get("Auth::PersonaReLogin") : lang.get("Auth::LogOut")))) :
                    (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement("div", { className: "eris-auth-notice" + (state.errors.server ? "" : " hidden") },
                            react_1.default.createElement("div", { className: "eris-auth-notice-error" }, lang.get("Auth::ServerError")),
                            state.errors.server),
                        react_1.default.createElement("div", { className: "eris-auth-button" + (state.loading ? " eris-auth-loading" : ""), onClick: function () {
                                (type == 0 ? async.login : (type == 2 ? async.changePassword : async.register)).fetch();
                            } }, lang.get("Auth::LoginNow"))))))));
};
exports.Auth = Auth;
//# sourceMappingURL=auth.js.map