/**
 * common js of app(web).
 * The following is written.
 * 1.language
 * 2.loading
 * 3.alert
 * 4.url
 * 5.cms communication
 * 6.check if user is logged in
 * 
 * @since 1.4.3.2 & 1.4.3.3
 */

var CHK_Common = {};

CHK_Common.lang;

/**
 * get lang code in local storage
 * web gets lang form local storage
 * but app gets lnag from session storage
 */
CHK_Common.setLangCodeWeb = function() {
    let lang = CHK_Common.getLangWeb();
    if (lang.split("-")[0] == CHK_CONSTANT.LANG.English) {
        lang = CHK_CONSTANT.LANG.ENGLISH;
    } else if (lang.split("-")[0] == CHK_CONSTANT.LANG.KOREA) {
        lang = CHK_CONSTANT.LANG.KOREA;
    } else {
        lang =CHK_CONSTANT.LANG.JAPAN;
    }

    CHK_Common.lang = lang; 
}

/**
 * get lang in local storage
 * 
 * @returns String pageLang
 */
CHK_Common.getLangWeb = function() {
	let pageLang;
    if (!CHK_Common.lang) {
        if (localStorage[CHK_CONSTANT.LANG.SAVE_NAME]) {
            pageLang = localStorage[CHK_CONSTANT.LANG.SAVE_NAME];
		}
		else {
            pageLang = (window.navigator.languages && window.navigator.languages[0]) ||
            window.navigator.language ||
            window.navigator.userLanguage ||
            window.navigator.browserLanguage;
			localStorage[CHK_CONSTANT.LANG.SAVE_NAME] = pageLang;
		}
	}
    
	return pageLang;
}

/**
 * change lang of html 
 */
 CHK_Common.updateLang = function() {
	
	$(".multi-lang").each(function () {
        const key = $(this).attr("data-msg");
		if (key) {
            if ($(this).prop("tagName").toLowerCase() == "input" && ($(this).attr("type") == "text" || $(this).attr("type") == "search")) {
                const attr = $(this).attr('placeholder');
				if (typeof attr !== 'undefined' && attr !== false) {
                    $(this).attr("placeholder", CHK_Common.getMsg(key));
				} else {
                    $(this).val(CHK_Common.getMsg(key));
				}
			} else {
                $(this).html(CHK_Common.getMsg(key));
			}
		}
	});
}

/**
 * get any lang msg from CHK_Common.msgMap
 * 
 * @param String key 
 * @returns String msg
 */
CHK_Common.getMsg = function (key) {
    const msg = CHK_CONSTANT.MSG_MAP[key];
    if (!msg) {
		return "";
    }
	
    return msg[CHK_Common.lang];
}

/**
 * show loading dialog
 * show msg by key
 * 
 * @param {String} key 
 */
CHK_Common.showLoading = function() {
	$("#check_loading").dialog({
		dialogClass: 'noTitleDialog ui-dialog-titlebar dialogNoBorder',
		autoOpen: false,
		resizable: false,
		modal: true,
		width: "100%",
		title: ' ',
		open: function(e) {
			$('.loadingAnime .loadingBall').css('animation-play-state','');
			$(e.target).parent().css('background-color', 'rgba(128,128,128)');
			$(e.target).parent().css('position', 'absolute');
			$(e.target).parent().css('left', '50%');
			$(e.target).parent().css('top', '25vh');
			$(e.target).parent().css('transform', 'translateX(-50%)');
			$(e.target).parent().css('-webkit- transform', 'translateY(-50%) translateX(-50%)');
			$(e.target).parent().children(".ui-dialog-buttonpane").css('background-color', 'rgba(128,128,128)').css('border', 'none');
		},
		close: function() {}
	});

	$("#check_loading").dialog('open');
}

/**
 * close loading 
 */
CHK_Common.closeLoading = function() {
	if ($("#check_loading").hasClass("ui-dialog-content")) {
		$("#check_loading").dialog('close');
		$('.loadingAnime .loadingBall').css('animation-play-state','paused');
	}
}

/**
 * show alert
 * 
 * @param {String} msgCode 
 */
 CHK_Common.displayAlert = function(msgCode) {
	
	$("#alertMsg").html(CHK_Common.getMsg(msgCode));
	$(".alert-overlay").removeClass("d-none");
	$(".alert-area").removeClass("d-none");
	
	const positionY = $(document).scrollTop() + screen.height/8;
	const height = screen.height/4;
	$(".alert-overlay").css("height", screen.height);
	$(".alert-area").css("top", positionY);
	$(".alert-area").css("min-height", height);
	$("body").css("overflow", "hidden");
}

/**
 * close alert
 */
CHK_Common.alertClose = function() {
	$(".alert-overlay").addClass("d-none");
    $(".alert-area").addClass("d-none");
	$("body").css("overflow", "visible");
}

/**
 * send ABookCheck
 * 
 * @param {json} param 
 * @param {boolean} async 
 * @param {Object} callback
 * @param {Object} errorCallback
 */
 CHK_Common.sendABookCheckApi = function(param, async = true, callback, errorCallback) {
	
	const url = CHK_Common.getUrlWeb(param.cmd);
	CHK_Common.cmsAjax(url, param, async, callback, errorCallback); 
}

/**
 * get URL for CMS action
 * @param {String} method
 */
CHK_Common.getUrlWeb = function(method) {

	for (let i in CHK_CONSTANT.CMS_WEB) {
	
		if (CHK_CONSTANT.CMS_WEB[i].includes(method)) {
			return "https://" + location.host + "/checkapi/web/" + CHK_CONSTANT.CMS_WEB[i] + "/" + method;
			
		}
	}

	return null;
}

/**
 * go Url page With Current Params
 * 
 * ios will remove all web types data when reopen webview
 * need add common parameters: app, lang, debug, mobile_flg, isChat, ...
 * 
 * @param {String} url
 * @param {Object} params
 */
CHK_Common.goUrlWithCurrentParams = function(url, params) {	

	if (!params) {
		location.href = url;
	}
	const mixParams = Object.assign(CHK_Common.getUrlParameter(), params);	
	if (url.includes("?")) {	
		location.href = url + '&' + new URLSearchParams(mixParams);	
	} else {	
		location.href = url + '?' + new URLSearchParams(mixParams);	
	}	
}

/**
 * get url parameter
 *
 */
CHK_Common.getUrlParameter = function() {
	var ret = {};
	if (location.search) {
		var param = {};
		location.search.substring(1).split('&').forEach(function(val) {
			var kv = val.split('=');
			param[kv[0]] = kv[1];
		});
		ret = param;
	}
	console.log({ret: ret});
	return ret;
}

/**
 * get sid in local Storage
 * 
 * @returns sid
 */
CHK_Common.getSid = function() {
	return "sid";
}

/**
 * cms communication
 * 
 * @param {String} url 
 * @param {Json} param 
 * @param {boolean} async 
 * @param {Object} callback
 * @param {Object} errorCallback
 */
CHK_Common.cmsAjax = function(url, param, async = true, callback, errorCallback) {
	if (url) {

		$.ajax({
			type: "POST",
			url: url,
			data: param,
			dataType:"json",
			cache: false,
			async: async,
			success: function(result) {
				if (result.status == "200") {
					if(callback) callback(result);
				} else if (result.status == "401") {
						location.href = "/login.html";
				} else if(errorCallback) {
					errorCallback();
				} else {
					CHK_Common.closeLoading();
					CHK_Common.displayAlert(result.message);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//if(errorCallback) {
					//errorCallback();
				//} else {
					CHK_Common.closeLoading();
					CHK_Common.displayAlert("errorCommunicationFailed");
				//}
			}
		});
	} else {
		if(errorCallback) {
			errorCallback();
		} else {
			CHK_Common.closeLoading();
			CHK_Common.displayAlert("errorOccurred");
		}
	}
}

/**
 * Communicate with cms and post
 * 
 * @param {String} url 
 * @param {Object} params 
 * @param {String} method 
 */
CHK_Common.postCommunication = function(url, params, method='post') {

	const form = document.createElement('form');
	form.method = method;
	form.action = url;

	for (const key in params) {
		if (params.hasOwnProperty(key)) {
			const hiddenField = document.createElement('input');
			hiddenField.type = 'hidden';
			hiddenField.name = key;
			hiddenField.value = params[key];
			form.appendChild(hiddenField);
		}
	}

	document.body.appendChild(form);
	form.submit();
};

/**
 * Check if user is logged in
 * 
 * @param {boolean} async 
 */
CHK_Common.checkAuth = function(async = true) {
	let params ={};
    params.sid = CHK_Common.getSid;
    params.cmd = CHK_CONSTANT.ACT_CMD.checkSession;
    CHK_Common.sendABookCheckApi(params, async, null, function() {
		CHK_Common.goUrlWithCurrentParams(CHK_CONSTANT.PAGE_NAME.LOGIN);
	});
}