<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">



<script th:fragment="view" th:inline="javascript" type="application/javascript">

    function deleteArticle() {

        if (confirm("글을 정말 삭제하시겠습니까?") == true) {
            document.getElementById("deleteArticle").submit();
        } else {
            return false;
        }


    }

</script>




<script th:fragment="comment" th:inline="javascript" type="application/javascript">

    const replyBox = document.getElementById("commentBox");

    document.addEventListener("DOMContentLoaded",
        function () {
            let token = getCsrfToken();
            let urlSearch = new URLSearchParams(location.search);
            let articleId = urlSearch.get("articleId");

            const xhr = new XMLHttpRequest();
            xhr.open("GET", "/comment/list/" + articleId);
            xhr.setRequestHeader("X-XSRF-TOKEN", token);
            xhr.send();

            xhr.onload = () => {
                makeCommentBox(xhr, replyBox);
            }
        }
    );

    function commentWrite() {
        let token = getCsrfToken();
        let content = document.getElementById("commentContent").value;
        let isSecret = document.getElementById("isCommentSecret").checked;

        // 댓글 내용 유효성 검사
        if(content === ""|| content ===" "){
            alert("댓글을 작성해주세요");
            return;
        }

        let commentForm = {};
        commentForm.content = content;
        commentForm.secret = isSecret;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/comment/write?articleId=" + [[${article.getId()}]]);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send(JSON.stringify(commentForm));

        xhr.onload = () => {
            if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {
                makeCommentBox(xhr, replyBox);
                document.getElementById("commentContent").value = '';
            }
            else{
                alert(xhr.response);
            }
        }
    }

    function cCommentWrite(parentCommentId) {
        let token = getCsrfToken();
        let content = document.getElementById("child-content-" + parentCommentId).value;
        let isSecret = document.getElementById("isCommentSecret-"+ parentCommentId).checked;


        let commentForm = {};
        commentForm.content = content;
        commentForm.secret = isSecret;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/comment/write?parentId=" + parentCommentId + "&articleId=" + [[${article.getId()}]]);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send(JSON.stringify(commentForm));

        xhr.onload = () => {
            makeCommentBox(xhr, replyBox);
            document.getElementById("commentContent").value = '';
        }
    }

    function deleteCommentConfirm(commentId) {

        if (confirm("댓글을 정말 삭제하시겠습니까?") === true) {
            deleteComment(commentId);
        } else {
            return false;
        }
    }

    function deleteComment(commentId) {
        let token = getCsrfToken();

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/comment/delete?commentId=" + commentId + "&articleId=" + [[${article.getId()}]]);
        xhr.setRequestHeader("content-type", "application/json");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send();

        xhr.onload = () => {
            makeCommentBox(xhr, replyBox);
        }
    }

    function makeCommentBox(xhr, replyBox) {

    const roleArr = [[${#authentication.authorities}]];

        if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {

            let commentList = JSON.parse(xhr.response);

            let member = null;
            if ([[${member}]] != null) {
                member = [[${member}]];
            }

            // 초기화
            replyBox.innerHTML = ' ';
// 부모 댓글 리스트
            let idx = 1;
            for (const parentComment of commentList) {
                let replyHtmlSource = ' ';

                parentComment.createdDate[1]--;
                let date = moment(parentComment.createdDate).format('YY-MM-DD HH:mm:ss');

                replyHtmlSource +=
                    `<div class="mt-2 comment-box" id="commentBox">
    <div class="d-flex flex-row p-2">
        <div>
            <img src="${parentComment.picUrl}" width="40" height="40"
                 class="rounded-circle me-2" alt="">
        </div>
        <div class="w-100">
            <div class="d-flex justify-content-between align-items-center">
                <span class="me-2">${parentComment.username}</span>
                <div class="d-flex flex-row align-items-center">
                    <small>${date}</small>`

                if (member != null && member.id === parentComment.memberId) {
                    replyHtmlSource +=
                        `<button class="btn p-0 m-0 fas fa-trash ms-3"
                            onclick="deleteCommentConfirm(${parentComment.id});return false">
                         </button>`
                }
                replyHtmlSource +=
                    `</div>
            </div>`

                // 부모 댓글 비밀댓글 처리
             if(parentComment.secret === true){
                 if(roleArr[0].authority === "ROLE_ADMIN") {
                     replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${parentComment.content}(비밀댓글입니다)</p>`
                 }
                 else if(member != null &&member.id === parentComment.memberId){
                     replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${parentComment.content}(내가 쓴 비밀댓글입니다)</p>`;
                 }
                 else{
                     replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">비밀댓글입니다.</p>`;
                 }
             }
            else{
                 replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${parentComment.content}</p>`
             }

            <!-- comment-reply-post -->
                replyHtmlSource +=
            `<div class="comment-reply">
                <div style="background-color: #ebebeb;">
                    <button class="btn align-items-center rounded collapsed" data-bs-toggle="collapse"
                            data-bs-target="#comment-reply-${parentComment.id}" aria-expanded="false">
                        <i class="fa fa-comments-o me-2"></i> 대댓글
                    </button>
                </div>`


                if (member != null) {
                    replyHtmlSource +=
                        `<div class="collapse" id="comment-reply-${parentComment.id}">
                    <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
                        <li>
                            <div class="mt-3 d-flex flex-row align-items-center p-2 form-color">
                                <div>
                                </div>
                                <textarea id="child-content-${parentComment.id}" name="child-content-${parentComment.id}" class="form-control" placeholder="대댓글을 작성해주세요..."></textarea>
                            </div>

                            <div class="d-flex">

                <div class="ms-1 mt-2 secretBox">
                    <label class="lock">
                        <input type="checkbox" id="isCommentSecret-${parentComment.id}" value="true"/>
                        <span></span>
                    </label>
                </div>

                                <div class="ms-auto ms-1 me-2">
                                    <button class="btn btn-sm btn-secondary" onclick="cCommentWrite(${parentComment.id})">등 록</button>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>`
                }

                // 자식 댓글 리스트
                for (const childComment of parentComment.commentDtoList) {

                    childComment.createdDate[1]--;
                    let date = moment(childComment.createdDate).format('YY-MM-DD HH:mm:ss');

                    replyHtmlSource +=
                        `<div class="d-flex flex-row p-2">
                <div>
                    <img src="${childComment.picUrl}" width="40"
                         height="40" class="rounded-circle me-2" alt="">
                </div>
                <div class="w-100">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="me-2">${childComment.username}</span>
                        <div class="d-flex flex-row align-items-center">
                            <small>${date}</small>`

                    if (member != null && member.id === childComment.memberId) {
                        replyHtmlSource +=
                            `<button class="btn p-0 m-0 fas fa-trash ms-3"
                                        onclick="deleteCommentConfirm(${childComment.id});return false">
                                     </button>`
                    }
                    replyHtmlSource +=
                        `</div>
                    </div>`

                    // 자식댓글 비밀댓글 처리
                    if(childComment.secret === true){
                        if(roleArr[0].authority === "ROLE_ADMIN"||member != null &&member.id === parentComment.memberId) {
                            replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${childComment.content}(비밀댓글입니다)</p>`
                        }
                        else if(member != null &&member.id === childComment.memberId){
                            replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${childComment.content}(내가 쓴 비밀댓글입니다)</p>`;
                        }
                        else{
                            replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">비밀댓글입니다.</p>`;
                        }
                    }
                    else{
                        replyHtmlSource +=`<p class="text-justify comment-text mb-0" style="white-space:pre-wrap;">${childComment.content}</p>`
                    }

                    replyHtmlSource +=
                `</div>
            </div>`
                }

                // 부모댓글 리스트 마무리
                replyHtmlSource +=
                    `</div>
            </div>
        </div>
    </div> `
//

                replyBox.innerHTML += replyHtmlSource;
            }
        }
    }

</script>


<script th:fragment="articleEdit" th:inline="javascript" type="application/javascript">

    const contents = document.getElementById("content");

    toastui.Editor.setLanguage(['ko', 'ko-KR'], {
        Markdown: '마크다운',
        WYSIWYG: '일반',
        Write: '편집하기',
        Preview: '미리보기',
        Headings: '제목크기',
        Paragraph: '본문',
        Bold: '굵게',
        Italic: '기울임꼴',
        Strike: '취소선',
        Code: '인라인 코드',
        Line: '문단나눔',
        Blockquote: '인용구',
        'Unordered list': '글머리 기호',
        'Ordered list': '번호 매기기',
        Task: '체크박스',
        Indent: '들여쓰기',
        Outdent: '내어쓰기',
        'Insert link': '링크 삽입',
        'Insert CodeBlock': '코드블럭 삽입',
        'Insert table': '표 삽입',
        'Insert image': '이미지 삽입',
        Heading: '제목',
        'Image URL': '이미지 주소',
        'Select image file': '이미지 파일을 선택하세요.',
        'Choose a file': '파일 선택',
        'No file': '선택된 파일 없음',
        Description: '설명',
        OK: '확인',
        More: '더 보기',
        Cancel: '취소',
        File: '파일',
        URL: '주소',
        'Link text': '링크 텍스트',
        'Add row to up': '위에 행 추가',
        'Add row to down': '아래에 행 추가',
        'Add column to left': '왼쪽에 열 추가',
        'Add column to right': '오른쪽에 열 추가',
        'Remove row': '행 삭제',
        'Remove column': '열 삭제',
        'Align column to left': '열 왼쪽 정렬',
        'Align column to center': '열 가운데 정렬',
        'Align column to right': '열 오른쪽 정렬',
        'Remove table': '표 삭제',
        'Would you like to paste as table?': '표형태로 붙여 넣겠습니까?',
        'Text color': '글자 색상',
        'Auto scroll enabled': '자동 스크롤 켜짐',
        'Auto scroll disabled': '자동 스크롤 꺼짐',
        'Choose language': '언어 선택',
    })

    const editor = new toastui.Editor({
        el: document.querySelector('#editor'),
        height: '800px',
        initialEditType: 'markdown',
        previewStyle: 'vertical',
        language: 'ko',
        toolbarItems: [
            ['heading', 'bold', 'italic', 'strike'],
            ['hr'],
            ['ul', 'ol'],
            ['code'],
            ['table', 'image', 'link']
        ],
        hooks: {
            addImageBlobHook: (blob, callback) => {
                let imgurl = uploadImage(blob);
                callback(imgurl, "첨부 이미지")
            }
        }
    });

    // 유효성 검사
    function checkTitle() {
        return document.getElementById("title").value !== "";
    }

    function checkContent() {

        if(contents.value.length >=  65535 ){
            return false;
        }
        return contents.value !== "";
    }

    function checkCategory() {
        return document.getElementById("category").value !== "카테고리를 선택해주세요";
    }

    function checkTags() {
        return document.getElementById("tags").value !== "";
    }

    //내부 이미지 업로드
    function uploadImage(blob) {
        let token = getCsrfToken();
        let formData = new FormData();
        formData.append('img', blob);

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/article/uploadImg", false);
        xhr.setRequestHeader("contentType", "multipart/form-data");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send(formData);

        if (xhr.readyState === 4 && xhr.status === 200) {
            return xhr.response;
        } else {
            alert("이미지가 정상적으로 업로드되지 못했습니다.")
        }
    }


    // 전송
    function post() {

        contents.value = editor.getMarkdown();

        if (!checkTitle()) {
            alert("제목을 입력해주세요")
            return;
        }
        else if (!checkContent()) {
            alert("내용은 1~ 65535자 이하여야합니다.")
            return;
        }else if (!checkCategory()) {
            alert("카테고리를 입력해주세요")
            return;
        }else if (!checkTags()) {
            alert("태그를 입력해주세요")
            return;
        }

        document.getElementById("writeArticleForm").submit();
    }

    editor.setMarkdown([[${articleDto.getContent()}]]);

</script>


<script th:fragment="tag" th:inline="javascript" type="application/javascript">

    const tags = [[${tagsInput}]];
    let whitelist = [];
    for (let tag of tags) {
        whitelist.push(tag.name)
    }

    const input = document.querySelector('input[name="tags"]');

    const tagify = new Tagify(input, {
        whitelist:whitelist,
        maxTags: 10,
        dropdown: {
            maxItems: 100,
            classname: "tags-look",
            enabled: 0,
            closeOnSelect: true
        }
    });

</script>


<script th:fragment="articleWrite" th:inline="javascript" type="application/javascript">

    const contents = document.getElementById("content");

    toastui.Editor.setLanguage(['ko', 'ko-KR'], {
        Markdown: '마크다운',
        WYSIWYG: '일반',
        Write: '편집하기',
        Preview: '미리보기',
        Headings: '제목크기',
        Paragraph: '본문',
        Bold: '굵게',
        Italic: '기울임꼴',
        Strike: '취소선',
        Code: '인라인 코드',
        Line: '문단나눔',
        Blockquote: '인용구',
        'Unordered list': '글머리 기호',
        'Ordered list': '번호 매기기',
        Task: '체크박스',
        Indent: '들여쓰기',
        Outdent: '내어쓰기',
        'Insert link': '링크 삽입',
        'Insert CodeBlock': '코드블럭 삽입',
        'Insert table': '표 삽입',
        'Insert image': '이미지 삽입',
        Heading: '제목',
        'Image URL': '이미지 주소',
        'Select image file': '이미지 파일을 선택하세요.',
        'Choose a file': '파일 선택',
        'No file': '선택된 파일 없음',
        Description: '설명',
        OK: '확인',
        More: '더 보기',
        Cancel: '취소',
        File: '파일',
        URL: '주소',
        'Link text': '링크 텍스트',
        'Add row to up': '위에 행 추가',
        'Add row to down': '아래에 행 추가',
        'Add column to left': '왼쪽에 열 추가',
        'Add column to right': '오른쪽에 열 추가',
        'Remove row': '행 삭제',
        'Remove column': '열 삭제',
        'Align column to left': '열 왼쪽 정렬',
        'Align column to center': '열 가운데 정렬',
        'Align column to right': '열 오른쪽 정렬',
        'Remove table': '표 삭제',
        'Would you like to paste as table?': '표형태로 붙여 넣겠습니까?',
        'Text color': '글자 색상',
        'Auto scroll enabled': '자동 스크롤 켜짐',
        'Auto scroll disabled': '자동 스크롤 꺼짐',
        'Choose language': '언어 선택',
    })

    const editor = new toastui.Editor({
        el: document.querySelector('#editor'),
        height: '800px',
        initialEditType: 'markdown',
        previewStyle: 'vertical',
        language: 'ko',
        toolbarItems: [
            ['heading', 'bold', 'italic', 'strike'],
            ['hr'],
            ['ul', 'ol'],
            ['code'],
            ['table', 'image', 'link']
        ],
        hooks: {
            addImageBlobHook: (blob, callback) => {
                let imgurl = uploadImage(blob);
                callback(imgurl, "첨부 이미지")
            }
        }
    });

    //내부 이미지 업로드
    function uploadImage(blob) {
        let token = getCsrfToken();
        let formData = new FormData();
        formData.append('img', blob);

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/article/uploadImg", false);
        xhr.setRequestHeader("contentType", "multipart/form-data");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send(formData);

        if (xhr.readyState === 4 && xhr.status === 200) {
            return xhr.response;
        } else {
            alert("이미지가 정상적으로 업로드되지 못했습니다.")
        }
    }


    // 유효성 검사
    function checkTitle() {
        return document.getElementById("title").value !== "";
    }

    function checkContent() {

        if(contents.value.length >=  65535 ){
            return false;
        }
        return contents.value !== "";
    }

    function checkCategory() {
        return document.getElementById("category").value !== "카테고리를 선택해주세요";
    }

    function checkTags() {
        return document.getElementById("tags").value !== "";
    }

    // 전송
    function post() {

        contents.value = editor.getMarkdown();

        if (!checkTitle()) {
            alert("제목을 입력해주세요")
            return;
        }
        else if (!checkContent()) {
            alert("내용은 1~ 65535자 이하여야합니다.")
            return;
        }else if (!checkCategory()) {
            alert("카테고리를 입력해주세요")
            return;
        }else if (!checkTags()) {
            alert("태그를 입력해주세요")
            return;
        }

        document.getElementById("writeArticleForm").submit();
    }

    // 자동 저장 기능
    function autoSave(){

        let token = getCsrfToken();
        let tempDto = {};
        tempDto.content = editor.getMarkdown();

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/article/temp/autoSave")
        xhr.setRequestHeader("content-type", "application/json");
        xhr.setRequestHeader("X-XSRF-TOKEN", token);
        xhr.send(JSON.stringify(tempDto));

        xhr.onload = () => {

            if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {

                console.log("autoSave");

            }
        }

    }

    setInterval("autoSave()",60000);

    window.onload = function () {

        const xhr = new XMLHttpRequest();
        xhr.open("GET", "/article/temp/getTemp")
        xhr.send();

        xhr.onload = () => {
            if (xhr.status === 200 || xhr.status === 201 || xhr.status === 202) {

              let tmp = JSON.parse(xhr.response);

                if(tmp.content != null&& tmp.content !== ''){
                    let isLoadTmp = confirm("이전에 작성하던 글이 있습니다. 이어서 작성하시겠습니까?");
                    if(isLoadTmp){
                        editor.setMarkdown(tmp.content);
                    }
                }
            }
        }
    }

</script>


</html>