const { cryptchaSiteId } = require("../config-client")

/**
 *
 * @param {any} str
 */
function log(str) {
    console.log(JSON.stringify(str, undefined, 4))
}

/**
 * convert object to string
 * @param {any} obj object
 * @returns {string}
 */
function obj2str(obj) {
    if (Array.isArray(obj)) {
        return JSON.stringify(
            obj.map(function (idx) {
                return obj2str(idx)
            })
        )
    } else if (typeof obj === "object" && obj !== null) {
        var elements = Object.keys(obj)
            .sort()
            .map(function (key) {
                var val = obj2str(obj[key])
                if (val) {
                    return key + ":" + val
                }
            })

        var elementsCleaned = []
        for (var i = 0; i < elements.length; i++) {
            if (elements[i]) elementsCleaned.push(elements[i])
        }

        return "{" + elementsCleaned.join("|") + "}"
    }

    if (obj) return obj
}

/**
 * clear SSR cache
 * @returns {number}
 */
function clearSSRCache() {
    var info = context.db.deleteMany("ssr", {})
    context.response.header("X-SSR-Cleared", info.removed)
    return info.removed
}

function cryptchaCheck() {
    const solutionId = context.data._sId
    const solution = context.data._s

    const body = JSON.stringify({ solution: solution })
    console.log(body)
    const resp = context.http.fetch(
        "https://cryptcha.webmakers.de/api/command?siteId=" +
            cryptchaSiteId +
            "&cmd=check&clear=1&solutionId=" +
            solutionId,
        {
            method: "POST",
            body,
            headers: { "Content-Type": "application/json" },
        }
    )
    const j = resp.body.json()

    const corrent = j.status == "ok" && resp.status == 200
    if (!corrent) {
        throw {
            status: 400,
            log: false,
            error: "incorrect data",
        }
    }
    return true
}

module.exports = {
    log,
    clearSSRCache,
    obj2str,
    cryptchaCheck,
}
