var enc = null
var keyword = null
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginFormElement');
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault(); // 기본 폼 제출 동작 방지
        submitLoginForm();
    });
    if (document.querySelector(".rank_of_view")) {
        fetch('blog/rankOfViews.bjx')
            .then(response => response.json())
            .then(data => {
                const ul = document.querySelector('.rank_of_view');
                ul.innerHTML = ''; // 기존 리스트 지움
                ul.style.listStyle = 'none';  // 불릿 제거
                ul.style.paddingLeft = '0';   // 들여쓰기 제거 (선택사항)
                // data가 ['제목1', '제목2', ...] 형식이라고 가정
                data.posts.forEach(item => {
                    const date = new Date(item.writeTime);

                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');

                    const formatted = `${year}/${month}/${day}`;
                    const li = document.createElement('li');
                    const a = document.createElement('a');
                    a.id = item.id;
                    a.href = `${getMainPath()}/blog/viewer/${item.id}`;
                    a.innerHTML = `${item.title}<br>[${year}/${month}/${day}]`
                    li.appendChild(a);
                    ul.appendChild(li);
                });
            })
            .catch(error => {
                    console.error('받아오기 실패:', error);
                }
            );
    }
    if (document.querySelector(".recent_posts")) {
        fetch('blog/recentOfPost.bjx')
            .then(response => response.json())
            .then(data => {
                const ul = document.querySelector('.recent_posts');
                ul.innerHTML = ''; // 기존 리스트 지움
                ul.style.listStyle = 'none';  // 불릿 제거
                ul.style.paddingLeft = '0';   // 들여쓰기 제거 (선택사항)
                // data가 ['제목1', '제목2', ...] 형식이라고 가정
                data.posts.forEach(item => {
                    const date = new Date(item.writeTime);

                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');

                    const formatted = `${year}/${month}/${day}`;
                    const li = document.createElement('li');
                    const a = document.createElement('a');
                    a.id = item.id;
                    a.href = `${getMainPath()}/blog/viewer/${item.id}`;
                    a.innerHTML = `${item.title}<br>[${year}/${month}/${day}]`
                    li.appendChild(a);
                    ul.appendChild(li);
                });
            })
            .catch(error => {
                    console.error('받아오기 실패:', error);
                }
            );
    }

});
onload = function() {
    history.replaceState({}, null, location.pathname);
    // var accToken = get_cookie("access")
    // var refreshToken = get_cookie("refresh")
    // console.log("access === " + accToken + " || " + accToken.length);
    // console.log("refresh === " + refreshToken + " || " + refreshToken.length);
    document.cookie = "access=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"
    document.cookie = "refresh=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"
    document.cookie = "CLEAR=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"

    var currentList = [{"page":["posts"],"id":"menu_posts"},{"page":["licenses"],"id":"menu_drop"},{"page":["licenses"],"id":"menu_drop"}]
    if(location.pathname.length > 1) {
        // 1. 모든 'current' 클래스를 가진 요소를 선택하고 제거
        // const currentElements = document.querySelectorAll('.current');
        // currentElements.forEach(element => {
        //     element.classList.remove('current');
        // });
        currentList.forEach(element => {
            element.page.forEach((page, index) => {
                console.log(location.pathname);
                if (location.pathname.includes(page)) {
                    const targetElement = document.getElementById(element.id);
                    if (targetElement) {
                        targetElement.classList.add('current');
                    }
                }
            })
        })
    } else {
        const targetElement = document.getElementById('menu_home');
        if (targetElement) {
            targetElement.classList.add('current');
        }
    }
}
// onbeforeunload = function () {
//     var accToken = get_cookie("access")
//     var refreshToken = get_cookie("refresh")
//     console.log("access === " + accToken + " || " + accToken.length);
//     console.log("refresh === " + refreshToken + " || " + refreshToken.length);
//
//     if (accToken.length < 1) {
//         document.cookie = "refresh="+ window.sessionStorage.getItem("REFRESH") + ";";
//     }
//     if (refreshToken.length < 1) {
//         window.sessionStorage.setItem("REFRESH",get_cookie("refresh"))
//     }
// }

function sendTlg(form, type,keyword) {
    console.log(form)
    let data = {
        'name': form.querySelector("#name").value,
        'email': form.querySelector("#email").value,
        'message': form.querySelector("#message").value,
    }
    if (data.name != null && data.email != null && data.message != null && data.message.length > 0) {
        if(confirm(JSON.stringify(data) + "\n해당 내용으로\n메시지 보내쉴?")) {
            post(getMainPath()+"/tlg/repotToMe.bjx",type,JSON.stringify(data),keyword, function (resultData) {
                alert("서버에 전달됨.")
            })
        } else {

        }
    }
    return false
}
function get_cookie(name) {
    var value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return value? value[2] : null;
}
function divider(key) {
    return merge(padding(),key,padding())
}
function padding() {
    return "%7C%2A-%2A%7C";
}
function merge(...args) {
    return args.join("");
}
function unformat(type , data, key) {
    var even = [];
    var odd = [];
    data.split("").forEach(function (v,idx,full) {if(idx % 2 === 0) {even.push(v)} else {odd.push(v)}});
    switch (type) {
        case "T0": return merge(odd.join(""),divider(key),even.join(""));
        case "T1": return merge(odd.reverse().join(""),divider(key),even.join(""));
        case "T2": return merge(odd.join(""),divider(key),even.reverse().join(""));
        default: return merge(odd.reverse().join(""),divider(key),even.reverse().join(""));
    }
}
function checkDebug(){
    var debug = false
    try {
        debug = typeof v8debug === 'object'
            || /--debug|--inspect/.test(process.execArgv.join(' '));
        alert(debug)
    } catch (e) {

    }

    try {
        const inspector = require('inspector');
        debug  = inspector.url() !== undefined;
        alert(debug)
    } catch (e) {

    }
}
var acpt_key = ""
function post(target,type, data, key,callBackResult) {
    var httpRequest;
    /* 통신에 사용 될 XMLHttpRequest 객체 정의 */
    httpRequest = new XMLHttpRequest();
    /* httpRequest의 readyState가 변화했을때 함수 실행 */
    httpRequest.onreadystatechange = () => {
        /* readyState가 Done이고 응답 값이 200일 때, 받아온 response로 name과 age를 그려줌 */
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                callBackResult(httpRequest.response)
            } else {
                alert('Request Error!');
            }
        }
    }

    httpRequest.open('POST', target, true);
    httpRequest.setRequestHeader("Content-Type", "text/plain");
    var odd = []
    var even = []
    var dataStr = JSON.stringify(data)
    var src = dataStr.split("")
    src.forEach(function (s,i,a) {if (i % 2 === 0) {even.push(s)} else {odd.push(s)}})
    httpRequest.send(btoa(JSON.stringify({
        'data': unformat(type,data,key),
        'key':key,
        'type':type,
    })));
}
function postLogin(target,type, data, key,callBackResult) {
    var httpRequest;
    /* 통신에 사용 될 XMLHttpRequest 객체 정의 */
    httpRequest = new XMLHttpRequest();
    /* httpRequest의 readyState가 변화했을때 함수 실행 */
    httpRequest.onreadystatechange = () => {
        /* readyState가 Done이고 응답 값이 200일 때, 받아온 response로 name과 age를 그려줌 */
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                try {
                    var data = JSON.parse(httpRequest.response)
                    callBackResult(data)
                } catch (e) {

                }
            } else {
                alert('Request Error!');
            }
        }
    }

    httpRequest.withCredentials = true
    httpRequest.open('POST', target, true);
    httpRequest.setRequestHeader("Content-Type", "text/plain");
    var odd = []
    var even = []
    var dataStr = JSON.stringify(data)
    var src = dataStr.split("")
    src.forEach(function (s,i,a) {if (i % 2 === 0) {even.push(s)} else {odd.push(s)}})
    httpRequest.send(btoa(JSON.stringify({
        'data': unformat(type,data,key),
        'key':key,
        'type':type,
    })));
}

function mainPath() {
    console.log(`location.port >> ${location.port}`)
    if ('443' === location.port) {
        document.location.replace(location.protocol + "//" + location.hostname + ":" + location.port)
    } else {
        document.location.replace(location.protocol + "//" + location.hostname)
    }
}

function gotoWrite() {
    document.location.replace(getMainPath()+"/blog/write.bs")
}

function gotoModify() {
    document.location.replace(getMainPath()+"/blog/modify.bs")
}

function gotoWhere() {
    document.location.replace(getMainPath()+"/bums/where.bs")
}

function logout() {
    // retrieve all cookies
    document.cookie = "access=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"
    document.cookie = "refresh=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"

    console.log(document.cookie["JSESSIONID"])
    document.cookie = "JSESSIONID=; expires=Thu, 01 Jan 1970 00:00:01 GMT;"
    document.cookie = "CLEAR="+Date.now()+"";
    let logOutUrl = getMainPath() + "/user/logout.bs";

    alert("로그아웃 됨요~! 빠염~!")

    // 동적으로 form 생성하여 POST 요청 전송
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = getMainPath() + '/user/logout.bs';

    // CSRF 토큰을 meta태그 등에서 얻어서 삽입 (예: <meta name="_csrf" content="토큰값">)
    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
    const csrfParam = document.querySelector('meta[name="_csrf_parameter"]').getAttribute('content');
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = csrfParam; // 예: "_csrf"
    csrfInput.value = csrfToken;
    form.appendChild(csrfInput);

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

function gotoHome() {
    console.log(`location.port >> ${location.port}`)
    location.href = getMainPath()+"/home.bs"
}

function gotoLogin() {
    console.log(`location.port >> ${location.port}`)
    location.href = getMainPath()+"/login.bs"
}

function gotoJoin() {
    document.location.replace(getMainPath() + "/user/join.bs")
}

function goToViewer(item) {
    location.href = getMainPath() + "/blog/viewer/" + item.id
}

function goToView(path,id) {
    location.href = path + id;
}
function onclickLogin(type, keyword) {
    let user_id = document.getElementById('user_id')
    let user_pw = document.getElementById('user_pw')
    let data = {
        'user_id': user_id.value,
        'user_pw': user_pw.value,
    }
    postLogin(getMainPath()+"/user/login.bjx",type,JSON.stringify(data),keyword, function (data) {
        if (data.isOk) {

            document.cookie = "access=" + data.token.split(";")[0]+";"
            // document.cookie = "refresh=" + data.refresh.split(";")[0]+";"
            // window.sessionStorage.setItem("ACCESS",data.refresh.split(";")[0])
            window.sessionStorage.setItem("REFRESH",data.refresh.split(";")[0])
            document.location.replace(document.location)
        } else {
            if (data.resultCode === 7100) {
                if(confirm(`너 누구임 정보 없는데?!\n${data.resultMsg}[${data.resultCode}]\n가입 할래!?`)){
                    document.location.replace(getMainPath() + "/user/join.bs")
                }
            } else {
                alert(`너 누구임?!\n${data.resultMsg}[${data.resultCode}]`)
            }
        }
    })
}


function getMainPath() {
    console.log(`location.port >> ${location.port}`)
    if ('443' === location.port) {
        return location.protocol + "//" + location.hostname + ":" + location.port
    } else {
        return  location.protocol + "//" + location.hostname
    }
}

function openPopup(a) {

    var $href = $(a).attr('to');
    document.querySelectorAll('[id*=popLayer]').forEach(function (v,k,p) {
        $(v).hide();
    });
    layer_popup($href);
}

function layer_popup(el){
    var $el = $(el);    //레이어의 id를 $el 변수에 저장

    var isDim = true ;//$(document).hasClass('dimBg'); //dimmed 레이어를 감지하기 위한 boolean 변수
    isDim ? $('.dim_layer').fadeIn() : $el.fadeIn();
    $el.show()
    var $elWidth = ~~($el.outerWidth()),
        $elHeight = ~~($el.outerHeight()),
        docWidth = $(document).width(),
        docHeight = $(document).height();

    // 화면의 중앙에 레이어를 띄운다.
    if ($elHeight < docHeight || $elWidth < docWidth) {
        $el.css({
            marginTop: -$elHeight /2,
            marginLeft: -$elWidth/2
        })
    } else {
        $el.css({top: 0, left: 0});
    }

    $el.find('a.btn_layerClose').click(function(){
        isDim ? $('.dim_layer').fadeOut() : $el.fadeOut(); // 닫기 버튼을 클릭하면 레이어가 닫힌다.
        return false;
    });

    $('.dimBg').click(function(){
        $('.dim_layer').fadeOut();
        return false;
    });
}

function urldecode(t){
    return decodeURI(t)
}

function openLoginPopup(formType) {

    document.getElementById('overlay').style.display = 'block';
    document.getElementById('loginForm').style.display = formType === 'login' ? 'block' : 'none';
    document.getElementById('signupForm').style.display = formType === 'signup' ? 'block' : 'none';

    if(formType === 'login') {
        const loginIdInput = document.getElementById('loginId');
        loginIdInput.focus();
    }
}

function closePopup() {
    document.getElementById('overlay').style.display = 'none';
}

function submitLoginForm() {
    let user_id = document.getElementById('loginId')
    let user_pw = document.getElementById('loginPassword')
    let rememberMe = document.getElementById('rememberMe')
    let data = {
        'user_id': user_id.value,
        'user_pw': user_pw.value,
        'rememberMe' : rememberMe.value,
    }
    postLogin(getMainPath()+"/user/login.bjx",user_pw.data,JSON.stringify(data),user_pw.data, function (data) {
        closePopup()
        if (data.isOk) {
            document.cookie = "access=" + data.token.split(";")[0]+";"
            window.sessionStorage.setItem("REFRESH",data.refresh.split(";")[0])
            document.location.replace(location.href)
        } else {
            if (data.resultCode === 7100) {
                if(confirm(`너 누구임 정보 없는데?!\n${data.resultMsg}[${data.resultCode}]\n가입 할래!?`)){
                    document.location.replace(getMainPath() + "/user/join")
                }
            } else {
                alert(`너 누구임?!\n${data.resultMsg}[${data.resultCode}]`)
            }
        }
    })
}

function isDelta(content) {
    try {
        // Delta는 JSON이면서 'ops'라는 키를 포함
        if (typeof content === "string") {
            content = JSON.parse(content);
        }
        return typeof content === "object" && content.ops !== undefined;
    } catch (e) {
        return false; // JSON 파싱 실패하면 마크업(HTML)으로 간주
    }
}