/**
 * Account Settings function js
 * @since cms:1.4.3.2&1.4.3.3 web:1.0
 **/

var SETTINGS = {};

// Init function of page
$(document).ready(function () {
    //Check if user is logged in
    COMMON.checkAuth(false);
    SETTINGS.getToken();
    SETTINGS.initScreen();
    $('#dspPwdUpd1').click(SETTINGS.dspPwdUpd1_Click);
    COMMON.closeLoading();
});

/**
 * Get CSRF token from CMS server
 */
SETTINGS.getToken = function () {
    var params = {
        sid: ClientData.userInfo_sid(),
    };
    const url = COMMON.format(ClientData.conf_checkApiUrl(), ClientData.userInfo_accountPath()) + CONSTANT.URL.CMS.API.PASSWORD_GET_TOKEN;
    COMMON.cmsAjax(url, params, false, 
    function(data) {
        if (data.token) {
            $('#getToken').val(data.token);
        } else {
            COMMON.showAlert("errorGetToken");
        }
    }, 
    function(data) {
        if (data.errorMessage) {
            COMMON.showAlert(data.errorMessage);
        } else {
            COMMON.showAlert("errorGetToken");
        }
    });
};
/**
 * Process changing password
 * @param {*} e
 */
SETTINGS.dspPwdUpd1_Click = function (e) {
    // const tokenVal = $('#tokenVal').val();
    e.preventDefault();
    var isOK = true;
    var msgError = $('#main-error-message');
    // Check validation
    if (!ValidationUtil.CheckRequiredForText(SETTINGS.getCurrentPassword())) {
        isOK = false;
        msgError.html(COMMON.format(I18N.i18nText('msgEssential'), I18N.i18nText('txtPwdCurr')).toString());
        msgError.show();
    } else {
        if (!ValidationUtil.CheckRequiredForText(SETTINGS.getNewPassword())) {
            isOK = false;
            msgError.html(COMMON.format(I18N.i18nText('msgEssential'), I18N.i18nText('txtPwdNew')).toString());
            msgError.show();
        } else if (!ValidationUtil.CheckRequiredForText(SETTINGS.getNewPasswordRe())) {
            isOK = false;
            msgError.html(COMMON.format(I18N.i18nText('msgEssential'), I18N.i18nText('txtPwdNewRe')).toString());
            msgError.show();
        } else {
            if (SETTINGS.getNewPassword() != SETTINGS.getNewPasswordRe()) {
                isOK = false;
                msgError.html(I18N.i18nText('msgPwdNotMatch'));
                msgError.show();
            }
        }
    }
    if (isOK) {
        // Check min length
        if (!ValidationUtil.CheckMinLengthForByte(SETTINGS.getNewPassword(), 6)) {
            isOK = false;
            msgError.html(I18N.i18nText('msgInvaildLength'));
            msgError.show();
        }
        // Check max length
        if (!ValidationUtil.CheckMaxLengthForByte(SETTINGS.getNewPassword(), 16)) {
            isOK = false;
            msgError.html(I18N.i18nText('msgInvaildLength'));
            msgError.show();
        }
        // Check at least 3 consecutive characters
        if (ValidationUtil.HasSeqChar(SETTINGS.getNewPassword(), 3)) {
            isOK = false;
            msgError.html(I18N.i18nText('msgHasSeqChar'));
            msgError.show();
        }
        // Check 4 same characters in before password
        if (ValidationUtil.ContainSameSeqChar(SETTINGS.getCurrentPassword(), SETTINGS.getNewPassword(), 4)) {
            isOK = false;
            msgError.html(I18N.i18nText('msgContainSameSeqChar'));
            msgError.show();
        }
    }

    // Do changing password
    
    if (isOK) {
        var getToken = $("#getToken").val();
        var params = {
            sid: ClientData.userInfo_sid(),
            loginId: ClientData.userInfo_loginId_session(),
            password: SETTINGS.getCurrentPassword(),
            newPassword: SETTINGS.getNewPassword(),
            language: I18N.getCurrentLanguage(),
            token: getToken,
            appId: 4,
        };
        const url = COMMON.format(ClientData.conf_checkApiUrl(), ClientData.userInfo_accountPath()) + CONSTANT.URL.CMS.API.PASSWORD_CHANGE;
        COMMON.cmsAjax(url, params, false, SETTINGS.avwCmsApi_passwordChange_success, SETTINGS.avwCmsApi_passwordChange_fail);
    } else {
        //alert('error');
    }
};

/**
 * password change success
 * @param {*} data
 */
SETTINGS.avwCmsApi_passwordChange_success = function (data) {
    // OK
    var msgError = $('#main-error-message');

    if (data.httpStatus != CONSTANT.HTTP_STATUS.OK) {
        msgError.html(I18N.i18nText('msgPwdChangeNG'));
        msgError.show();
    } else {
        msgError.html('');
        $('#txtPwdCur').val('');
        $('#txtPwdNew').val('');
        $('#txtPwdNewRe').val('');
        /* show messages */
        COMMON.showAlert('msgPwdChangeOK',{titleCode: I18N.i18nText('success')});
    }
};

/**
 * password change fail
 * @param {*} xhr
 * @param {*} b
 * @param {*} c
 */
SETTINGS.avwCmsApi_passwordChange_fail = function (xhr, b, c) {
    /* show error messages */
    var msgError = $('#main-error-message');
    if (xhr.errorMessage && xhr.httpStatus != 0) {
        msgError.html(xhr.errorMessage);
    } else {
        msgError.html(I18N.i18nText('msgPwdChangeNG'));
    }
    msgError.show();
};

/*
----------------------------------------------------------------------------
Event groups [ end ]
----------------------------------------------------------------------------
*/

// Get input current password
SETTINGS.getCurrentPassword = function () {
    return $('#txtPwdCur').val();
};
// Get input new password
SETTINGS.getNewPassword = function () {
    return $('#txtPwdNew').val();
};
// Get input new password
SETTINGS.getNewPasswordRe = function () {
    return $('#txtPwdNewRe').val();
};

// Initalize screen
SETTINGS.initScreen = function () {
    TEMPLATE.loadHeader('#includedHeader');
    TEMPLATE.loadConfirmModal('#includedConfirmModal');
    const navs = [
        {
            titleLang: 'txtTooltipBack',
            href: 'javascript:history.back();',
        },
        {
            titleLang: 'accountSetting',
        },
    ]
    TEMPLATE.loadMainNavsTitle('#includedMainTitle', 'accountSetting', navs, null);
    // Login ID
    $('#txtLoginId').text(ClientData.userInfo_loginId_session());
    // Account Path
    $('#txtLoginAccPath').text(ClientData.userInfo_accountPath_session());

    // Recent login date
    $('#txtLastLoginTime').text(ClientData.userInfo_lastLoginTime());
};
