
function toImage(json) {
    try {
        _toImage(json);
    } catch (e) {
        log(`err: ${e}`);
        _onFail();
    }
}

function _toImage(json) {
    log(`toImage: ${json}`);

    const jsonObj = JSON.parse(json);
    const content = _decodeBase64(jsonObj.content);

    log(`raw content: ${content}`);

    const node = document.getElementById('content');

    _renderHtml(node, content);

    html2canvas(node, { useCORS: true, scale: 3 }).then((canvas) => {
        canvas.toBlob((blob) => {
            _uploadImage(jsonObj, blob);
        }, 'image/jpeg', 0.9);
    })
}

/**
 * 将html渲染到node
 *
 * @param {Element} node
 * @param {string} htmlContent
 */
function _renderHtml(node, htmlContent) {
    const options = {
        delimiters: [
            { left: "$$", right: "$$", display: true },
            { left: "$", right: "$", display: false },
            { left: "\\begin{equation}", right: "\\end{equation}", display: true },
            { left: "\\begin{align}", right: "\\end{align}", display: true },
            { left: "\\begin{alignat}", right: "\\end{alignat}", display: true },
            { left: "\\begin{gather}", right: "\\end{gather}", display: true },
            { left: "\\(", right: "\\)", display: false },
            { left: "\\[", right: "\\]", display: true }
        ]
    };

    node.innerHTML = htmlContent;

    renderMathInElement(node, options);
}

function _uploadImage(jsonObj, blob) {
    const formData = new FormData();
    formData.append('image', blob);

    const url = jsonObj.upload_url;
    fetch(url, {
        method: 'POST',
        body: formData
    }).then(response => {
        if (response.ok) {
            log('Image uploaded successfully');
            _md5(blob).then(md5 => {
                log(`MD5: ${md5}`);
                // notify app
                const result = {}
                result.id = jsonObj.id
                result.type = jsonObj.type
                // 计算 blob md5
                result.hash = md5
                app.onConvertImageFinish(JSON.stringify(result))
            })
        } else {
            log('Image upload failed');
            _onFail();
        }
    }).catch(error => {
        log(`Error: $error`);
        _onFail();
    });
}

function _md5(blob) {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = function (e) {
            const md5 = SparkMD5.ArrayBuffer.hash(e.target.result);
            resolve(md5);
        };
        fileReader.onerror = function (e) {
            reject(new Error('读取文件失败'));
        };
        fileReader.readAsArrayBuffer(blob);
    });
}

function _decodeBase64(src) {
    return decodeURIComponent(escape(window.atob(src)));
}

function _onFail() {
    app.onConvertImageFinish("")
}

const __isDebug = true;
function log(msg) {
    if (__isDebug) {
        console.log(msg)
    }
}