
var quill = null
function initEditor(useEditor) {
    console.log("DOMContentLoaded");
    const editorContainer = document.querySelector('#editor');
    function setEditorHeight() {
        const height = Math.max(window.innerHeight * 0.5, 300);
        editorContainer.style.height = height + 'px';
    }

    baseData.id = serverData.id;
    baseData.title = decodeURIComponent(serverData.title || '');
    baseData.content = decodeURIComponent(serverData.content || '');
    baseData.firstPostLat = serverData.firstPostLat;
    baseData.firstPostLon = serverData.firstPostLon;
    baseData.writeTime = serverData.writeTime;

    getLocation();

    setEditorHeight();
    window.addEventListener('resize', setEditorHeight);
    var Font = Quill.import('formats/font');
    Font.whitelist = ['sans-serif', 'serif', 'monospace', 'arial', 'georgia', 'comic-sans-ms', 'courier-new', 'roboto', 'playfair-display'];
    Quill.register(Font, true);
    Quill.register({ 'modules/table-better': QuillTableBetter }, true);

    quill = new Quill(editorContainer, {
        theme: 'snow',
        modules: useEditor ? {
            toolbar: {
                container: [
                    [{ font: Font.whitelist }],
                    [{ 'size': ['small', false, 'large', 'huge'] }],
                    ['bold', 'italic', 'underline', 'strike'],
                    [{ 'color': [] }, { 'background': [] }],
                    [{ 'header': 1 }, { 'header': 2 }, 'blockquote', 'code-block'],
                    [{ 'script': 'sub'}, { 'script': 'super' }],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    [{ 'indent': '-1'}, { 'indent': '+1' }],
                    ['link', 'image', 'video'],
                    ['table-better'],
                    [{ 'direction': 'rtl' }],
                    [{ 'align': [] }],
                    ['clean']
                ],
                handlers: {
                    image: function () {
                        selectLocalImage();
                    },
                    video: function () {
                        selectLocalVideo()
                    }
                }
            },
            'table-better': {
                language: 'en_US',
                toolbarTable: true
            },
            keyboard: {
                bindings: QuillTableBetter.keyboardBindings
            }
        } : {toolbar : false, toolbarTable: false},

        readOnly: !useEditor
    });

    loadContent(serverData.content);
    if (!useEditor) {
        editorContainer.classList.add('readonly-mode');
    } else {
        editorContainer.classList.remove('readonly-mode');
    }
    console.log("quill", quill);
}

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)으로 간주
    }
}


function loadContent(content) {
    if (isDelta(content)) {
        quill.setContents(content);                  // Delta 데이터라면 setContents
    } else {
        quill.clipboard.dangerouslyPasteHTML(content); // HTML 데이터라면 dangerouslyPasteHTML
    }
}

function save() {
    onclickWrite(serverData.enc ,serverData.keyword,quill.getContents())
}

function selectLocalImage() {
    // 이미지 URL 입력 받기
    const url = prompt("이미지 URL을 입력하거나 빈칸으로 두시면 파일 업로드를 합니다.");

    if (url) {
        // URL이 입력된 경우 이미지 삽입
        const range = quill.getSelection(true);
        quill.insertEmbed(range.index, 'image', url);
        quill.setSelection(range.index + 1);
    } else {
        // URL이 없거나 취소한 경우 파일 업로드 처리
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();

        input.onchange = async () => {
            const file = input.files[0];
            if (file) {
                const file = input.files[0];
                console.log("on selectLocalImage File", file);
                if (!file || !file.type.startsWith('image/')) {
                    console.warn('이미지 파일만 업로드 가능합니다.');
                    return;
                }
                uploadImage(file);
            }
        };
    }
}

function uploadImage(blob) {
    const formData = new FormData();
    formData.append('file', blob);
    let uploadUrl = getMainPath() + "/blog/post/imageUpload.bjx";
    let imageUrl = getMainPath() + '/blog/post/images/';
    $.ajax({
        type: 'POST',
        enctype: 'multipart/form-data',
        url: uploadUrl,
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        success: function (data) {
            console.log(data);
            imageUrl += data.fileName;
            insertToEditor(imageUrl);
        },
        error: function (e) {
            console.error(e);
            // callback('image_load_fail');
        }
    });
}

function selectLocalVideo() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'video/*');
    input.click();

    input.onchange = () => {
        const file = input.files[0];
        if (!file || !file.type.startsWith('video/')) {
            alert('동영상 파일만 업로드할 수 있습니다.');
            return;
        }
        uploadVideo(file);
    };
}
function uploadVideo(file) {
    const formData = new FormData();
    formData.append('video', file);

    fetch('/api/upload/video', {
        method: 'POST',
        body: formData
    })
        .then(res => res.json())
        .then(result => {
            if (result.url) {
                const range = quill.getSelection(true);
                quill.insertEmbed(range.index, 'video', result.url);
                quill.setSelection(range.index + 1);
            } else {
                console.error('동영상 업로드 실패', result);
            }
        })
        .catch(err => {
            console.error('업로드 중 오류', err);
        });
}


function insertToEditor(url) {
    const range = quill.getSelection(true);
    quill.insertEmbed(range.index, 'image', url);
    quill.setSelection(range.index + 1);
}

var currentLat = 0.0
var currentLon = 0.0

let baseData = {
    'id' : "",
    'title': "",
    'content': "",
    'firstPostLat': 0.0,
    'firstPostLon': 0.0,
    'category' : "none",
    'hashTags' : "#none",
    'modifyLat' : 0.0,
    'modifyLon' : 0.0,
    'originId' : "",
    'writeTime' : 0,
}

function goToEditor(element) {
    const postId = element.getAttribute('data-post-id');
    if (postId) {
        // postId를 이용해 원하는 처리 수행
        console.log("편집할 postId:", postId);
        // 예: 페이지 이동, 모달 오픈 등
        location.href = getMainPath() + '/blog/editor/' + postId;
    } else {
        console.warn("postId가 없네요.");
    }
}


function onclickWrite(type, keyword, html) {
    let title_field = document.getElementById('title_field')
    var hasValues = true
    if (hasValues) {
        baseData.title = encodeURIComponent(title_field.value)
        baseData.content =  encodeURIComponent(html)
        baseData.firstPostLat = encodeURIComponent(currentLat)
        baseData.firstPostLon = encodeURIComponent(currentLon)
    }
    let uploadUrl = getMainPath() + "/blog/post.bjx";
    if(confirm(JSON.stringify(baseData) + "\n해당 내용으로\n유저 등록 하실??")) {
        post(uploadUrl,type,JSON.stringify(baseData),keyword, function (resultData) {
            alert(resultData)
        })
    } else {

    }
}
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    currentLat = position.coords.latitude
    currentLon = position.coords.longitude
    if(baseData.firstPostLat !== 0.0) {
        baseData.modifyLat = encodeURIComponent(currentLat)
    }  else {
        baseData.firstPostLat = encodeURIComponent(currentLat)
    }
    if(baseData.firstPostLon !== 0.0 ) {
        baseData.modifyLon = encodeURIComponent(currentLon)
    }  else {
        baseData.firstPostLon = encodeURIComponent(currentLon)
    }


    document.getElementById('location_field').textContent = "Lat: " + position.coords.latitude + ", Lon: " + position.coords.longitude;
}