// let smallAppUrl =       `https://miniapp.bilibili.com/applet/debug/${sapprc.appId}_${sapprc.vAppId}?url=${encodeURIComponent(`http://${ip}:${port}/${zipLatestName}`)}`;
// let widgetUrl =         `bilibili://smallapp/test/widget/demo?openurl=${encodeURIComponent(`bilibili://smallapp/widget/debug/${sapprc.appId}?url=${encodeURIComponent(`http://${ip}:${port}/${zipName}`)}`)}`;
// let widgetPreviewURL =  `bilibili://smallapp/widget/preview?openurl=${encodeURIComponent(`bilibili://smallapp/widget/debug/${sapprc.appId}?url=${encodeURIComponent(`http://${ip}:${port}/${zipName}`)}`)}`;

const e = require("express");

const DEBUG_TYPE_LIST = ['sapp', 'applet', 'widget'];
const TYPE_MAPPING = {
    sapp: 'applet',
    applet: 'applet',
    widget: 'widget'
};

exports.getDebugUrl = function getDebugUrl ({
    type = 'sapp',
    // watch = false,
    preview = false,
    ip,
    port = 3000,
    zipName,
    sapprc = { appId: 'test',  vAppId: 'test' },
    storageId,
    embedBase = false
}) {
    type = getDebugType(type);
    let debugUrl = '';

    const myServerUrl = `http://${ip}:${port}/${zipName}`;
    if (storageId !== undefined) {
        debugUrl = `https://miniapp.bilibili.com/${TYPE_MAPPING[type]}/dev-${sapprc.appId}?_biliStorageId=${storageId}`;
    } else if (type === 'sapp') {
        debugUrl = `https://miniapp.bilibili.com/applet/debug/${sapprc.appId}_${sapprc.vAppId}?url=${encodeURIComponent(myServerUrl)}`;
    }
    // type === widget
    else if (preview) {
        debugUrl = `bilibili://smallapp/widget/predev-${sapprc.appId}?_biliFrom=testdev`;
        // debugUrl = `bilibili://smallapp/widget/preview?openurl=${encodeURIComponent(`bilibili://smallapp/widget/debug/${sapprc.appId}?url=${encodeURIComponent(myServerUrl)}`)}`;
    } else {
        debugUrl = `bilibili://smallapp/widget/debug/${sapprc.appId}?_biliFrom=testdev&url=${encodeURIComponent(myServerUrl)}`;
        // debugUrl = `bilibili://smallapp/test/widget/demo?openurl=${encodeURIComponent(`bilibili://smallapp/widget/debug/${sapprc.appId}?url=${encodeURIComponent(myServerUrl)}`)}`;
        // debugUrl = `bilibili://smallapp/widget/preview?openurl=${encodeURIComponent(`bilibili://smallapp/widget/debug/${sapprc.appId}?url=${encodeURIComponent(myServerUrl)}`)}`;
    }

    if (embedBase) {
        debugUrl += '&embed_base=1';
    }

    return debugUrl; 
};

function getDebugType (type) {
    type = type.toLowerCase();
    if (DEBUG_TYPE_LIST.includes(type)) return type;

    return DEBUG_TYPE_LIST[0];
}