"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "MoonrakerClient", {
    enumerable: true,
    get: function() {
        return MoonrakerClient;
    }
});
const _formdata = /*#__PURE__*/ _interop_require_default(require("form-data"));
const _eventconstants = require("../../constants/event.constants");
const _defaulthttpclientbuilder = require("../../shared/default-http-client.builder");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
class MoonrakerClient {
    httpClientFactory;
    eventEmitter2;
    settingsStore;
    logger;
    constructor(loggerFactory, httpClientFactory, eventEmitter2, settingsStore){
        this.httpClientFactory = httpClientFactory;
        this.eventEmitter2 = eventEmitter2;
        this.settingsStore = settingsStore;
        this.logger = loggerFactory(MoonrakerClient.name);
    }
    async getServerInfo(login) {
        return this.createClient(login).get("/server/info");
    }
    async getServerConfig(login) {
        return this.createClient(login).get("/server/config");
    }
    async getTemperatureStore(login, includeMonitors = false) {
        return this.createClient(login).get(`/server/temperature_store?include_monitors=${!!includeMonitors}`);
    }
    async getGcodeStore(login, count = 100) {
        return this.createClient(login).get(`/server/gcode_store?count=${count}`);
    }
    async postRolloverLogs(login, application = "") {
        return this.createClient(login).post(`server/logs/rollover`, {
            application
        });
    }
    async postRestartServer(login) {
        return this.createClient(login).post(`server/restart`);
    }
    async postJsonRpc(login, method, params, id) {
        return this.createClient(login).post(`server/jsonrpc`, {
            jsonrpc: "2.0",
            id: id ? id : 0,
            method,
            params
        });
    }
    async getPrinterInfo(login) {
        return this.createClient(login).post(`printer/info`);
    }
    async postQuickStop(login) {
        return this.createClient(login).post(`printer/emergency_stop`);
    }
    async postHostRestart(login) {
        return this.createClient(login).post(`printer/restart`);
    }
    async postFirmwareRestart(login) {
        return this.createClient(login).post(`printer/firmware_restart`);
    }
    async getPrinterObjectsList(login) {
        return this.createClient(login).get(`printer/objects/list`);
    }
    async getPrinterObjectsQuery(login, query) {
        const queryString = this.convertToQueryString(query);
        return this.createClient(login).get(`printer/objects/query?${queryString}`);
    }
    postSubscribePrinterObjects(login, connectionId, query) {
        const queryString = this.convertToQueryString(query);
        return this.createClient(login).post(`printer/objects/subscribe?connection_id=${connectionId}&${queryString}`);
    }
    async getPrinterQueryEndstops(login) {
        return this.createClient(login).get(`printer/query-endstops`);
    }
    async postGcodeScript(login, script = "G28") {
        return this.createClient(login).get(`printer/gcode/script?script=${script}`);
    }
    async getGcodeHelp(login) {
        return this.createClient(login).get(`printer/gcode/help`);
    }
    async postPrintStart(login, filename) {
        return this.createClient(login).post(`printer/print/start?filename=${filename}`);
    }
    async postPrintPause(login) {
        return this.createClient(login).post(`printer/print/pause`);
    }
    async postPrintResume(login) {
        return this.createClient(login).post(`printer/print/resume`);
    }
    async postPrintCancel(login) {
        return this.createClient(login).post(`printer/print/cancel`);
    }
    async getMachineSystemInfo(login) {
        return this.createClient(login).get(`machine/system_info`);
    }
    async postMachineShutdown(login) {
        return this.createClient(login).post(`machine/shutdown`);
    }
    async postMachineReboot(login) {
        return this.createClient(login).post(`machine/reboot`);
    }
    async postMachineRestartService(login, service) {
        return this.createClient(login).post(`machine/services/restart?service=${service}`);
    }
    async postMachineStartService(login, service) {
        return this.createClient(login).post(`machine/services/restart?service=${service}`);
    }
    async postMachineProcessStats(login) {
        return this.createClient(login).post(`machine/proc_stats`);
    }
    async getMachineSudoInfo(login, checkAccess = false) {
        return this.createClient(login).get(`machine/sudo/info?check_access=${checkAccess}`);
    }
    async postMachineSetSudoPassword(login, password) {
        return this.createClient(login).post(`machine/sudo/password`, {
            password
        });
    }
    async getMachineListPeripheralsUsb(login) {
        return this.createClient(login).get(`machine/peripherals/usb`);
    }
    async getMachineListPeripheralsSerial(login) {
        return this.createClient(login).get(`machine/peripherals/serial`);
    }
    async getMachineListPeripheralsVideo(login) {
        return this.createClient(login).get(`machine/peripherals/video`);
    }
    async getMachineListPeripheralsCanbus(login, canInterface = "can0") {
        return this.createClient(login).get(`machine/peripherals/canbus?interface=${canInterface}`);
    }
    async getServerFilesList(login, rootFolder = "") {
        const paramString = rootFolder?.length ? `?root=${rootFolder}` : "";
        return this.createClient(login).get(`server/files/list${paramString}`);
    }
    async getServerFilesRoots(login) {
        return this.createClient(login).get(`server/files/roots`);
    }
    async getServerFileMetadata(login, filename) {
        return this.createClient(login).get(`server/files/metadata?filename=${filename}`);
    }
    async getServerFileMetadataScan(login, filename) {
        return this.createClient(login).get(`server/files/metascan?filename=${filename}`);
    }
    async getServerFilesThumbnails(login, filename) {
        return this.createClient(login).get(`server/files/thumbnails?filename=${filename}`);
    }
    async getServerFilesDirectoryInfo(login, path, extended) {
        return this.createClient(login).get(`server/files/directory?path=${path}&extended=${extended}`);
    }
    async postServerFilesDirectory(login, path) {
        return this.createClient(login).post(`server/files/directory`, {
            path
        });
    }
    async deleteServerFilesDirectory(login, path, force) {
        return this.createClient(login).delete(`server/files/directory?path=${path}&force=${!!force}`);
    }
    async postServerFilesMove(login, source, dest) {
        return this.createClient(login).post(`server/files/directory`, {
            source,
            dest
        });
    }
    async postServerFilesCopy(login, source, dest) {
        return this.createClient(login).post(`server/files/copy`, {
            source,
            dest
        });
    }
    async postServerFilesZip(login, items, dest, store_only) {
        return this.createClient(login).post(`server/files/zip`, {
            items,
            store_only,
            dest
        });
    }
    async getServerFilesDownload(login, root, filename) {
        return await this.createClient(login).get(`server/files/${root}/${filename}`, {
            responseType: "stream"
        });
    }
    async getServerFilesDownloadChunk(login, root, filename, startBytes, endBytes) {
        return await this.createClient(login).get(`server/files/${root}/${filename}`, {
            headers: {
                Range: `bytes=${startBytes}-${endBytes}`
            }
        });
    }
    async postServerFileUpload(login, stream, fileName, contentLength, startPrint, progressToken, root, path, checksum) {
        const formData = new _formdata.default();
        if (root?.length) {
            formData.append("root", root);
        }
        if (path?.length) {
            formData.append("path", path);
        }
        if (checksum?.length) {
            formData.append("checksum", checksum);
        }
        if (startPrint) {
            formData.append("print", "true");
        }
        formData.append("file", stream, {
            filename: fileName,
            knownLength: contentLength
        });
        const result = await new Promise((resolve, reject)=>{
            return formData.getLength((err, length)=>{
                if (err) reject(new Error("Could not retrieve formData length"));
                resolve(length);
            });
        });
        try {
            const response = await this.createClient(login, (b)=>{
                b.withMultiPartFormData().withTimeout(this.settingsStore.getTimeoutSettings().apiUploadTimeout).withHeaders({
                    ...formData.getHeaders(),
                    "Content-Length": result.toString()
                }).withOnUploadProgress((p)=>{
                    if (progressToken) {
                        this.eventEmitter2.emit(`${(0, _eventconstants.uploadProgressEvent)(progressToken)}`, progressToken, p);
                    }
                });
            }).post(`server/files/upload`, formData);
            if (progressToken) {
                this.eventEmitter2.emit(`${(0, _eventconstants.uploadDoneEvent)(progressToken)}`, progressToken);
            }
            return response.data;
        } catch (e) {
            if (progressToken) {
                this.eventEmitter2.emit(`${(0, _eventconstants.uploadFailedEvent)(progressToken)}`, progressToken, e?.message);
            }
            let data;
            try {
                data = JSON.parse(e.response?.body);
            } catch  {
                data = e.response?.body;
            }
            throw new _runtimeexceptions.ExternalServiceError({
                error: e.message,
                statusCode: e.response?.statusCode,
                data,
                success: false,
                stack: e.stack
            }, "Moonraker");
        }
    }
    async deleteServerFile(login, root, path) {
        const url = `server/files/${root}/${path}`;
        return this.createClient(login).delete(url);
    }
    async getServerFileKlippyLogDownload(login) {
        return this.createClient(login).get(`server/files/klippy.log`);
    }
    async getServerFileMoonrakerLogDownload(login) {
        return this.createClient(login).get(`server/files/moonraker.log`);
    }
    async postAccessLoginUser(login, username, password, source = "moonraker") {
        return this.createClient(login).post("/access/login", {
            username,
            password,
            source
        });
    }
    async postAccessLogoutUser(login) {
        return this.createClient(login).post(`access/logout`);
    }
    async getAccessUser(login) {
        return this.createClient(login).get(`access/user`);
    }
    async postAccessCreateUser(login, username, password) {
        return this.createClient(login).post(`access/login`, {
            username,
            password
        });
    }
    async deleteAccessUser(login, username) {
        return this.createClient(login).delete(`access/user`, {
            data: {
                username
            }
        });
    }
    async listAccessUsers(login) {
        return this.createClient(login).get(`access/user/list`);
    }
    async postAccessResetPassword(login, refresh_token) {
        return this.createClient(login).post(`access/refresh_jwt`, {
            refresh_token
        });
    }
    async getAccessOneshotToken(login) {
        return this.createClient(login).get(`access/oneshot_token`);
    }
    async getAccessInfo(login) {
        return this.createClient(login).get(`access/info`);
    }
    async getAccessApiKey(login) {
        return this.createClient(login).get(`access/api_key`);
    }
    async postAccessApiKeyCreate(login) {
        return this.createClient(login).post(`access/api_key`);
    }
    async getDatabaseNamespaceList(login) {
        return this.createClient(login).get(`database/list`);
    }
    async getDatabaseNamespaceItem(login, namespace, key) {
        return this.createClient(login).get(`database/item?namespace=${namespace}&key=${key}`);
    }
    async postDatabaseNamespaceItem(login, namespace, key, value, typeHint) {
        const typeHintParam = typeHint?.length ? `:${typeHint}` : "";
        return this.createClient(login).post(`database/item?namespace=${namespace}&key=${key}&value${typeHintParam}=${value}`);
    }
    async deleteDatabaseNamespaceItem(login, namespace, key) {
        return this.createClient(login).delete(`database/item?namespace=${namespace}&key=${key}`);
    }
    async getJobQueueStatus(login) {
        return this.createClient(login).get(`job_queue/status`);
    }
    async postJobQueueJob(login, filenames, reset) {
        return this.createClient(login).post(`job_queue/job`, {
            filenames,
            reset
        });
    }
    async deleteJobQueueJob(login, jobIds, all) {
        const base = `job_queue/job`;
        const url = !!all ? `${base}?all=true` : `${base}?job_ids=${jobIds.join(",")}`;
        return this.createClient(login).delete(url);
    }
    async postJobQueuePause(login) {
        return this.createClient(login).post(`job_queue/pause`);
    }
    async postJobQueueStart(login) {
        return this.createClient(login).post(`job_queue/start`);
    }
    async postJobQueueJump(login, jobId) {
        return this.createClient(login).post(`job_queue/jump?job_id=${jobId}`);
    }
    async getAnnouncementsList(login, includeDismissed) {
        return this.createClient(login).get(`server/announcements/list?include_dismissed=${includeDismissed}`);
    }
    async postAnnouncementsUpdate(login) {
        return this.createClient(login).post(`server/announcements/update`);
    }
    async postAnnouncementsDismiss(login, entryId, wakeTime) {
        return this.createClient(login).post(`server/announcements/dismiss?entry_id=${encodeURIComponent(entryId)}&wake_time=${wakeTime}`);
    }
    async getAnnouncementsFeeds(login) {
        return this.createClient(login).get(`server/announcements/feeds`);
    }
    async postAnnouncementsFeedAdd(login, name) {
        return this.createClient(login).get(`server/announcements/feeds?name=${name}`);
    }
    async deleteAnnouncementsFeedRemove(login, name) {
        return this.createClient(login).delete(`server/announcements/feeds?name=${name}`);
    }
    async getWebcamList(login) {
        return this.createClient(login).get(`server/webcams/list`);
    }
    async getWebcamItem(login, uid, name) {
        const base = `server/webcams/get_item`;
        const url = !!uid?.length ? `${base}?uid=${uid}` : `${base}?name=${name}`;
        return this.createClient(login).get(url);
    }
    async postWebcamItemUpdate(login, webcam) {
        return this.createClient(login).post(`server/webcams/post_item`, webcam);
    }
    async deleteWebcamItem(login, uid, name) {
        const base = `server/webcams/delete_item`;
        const url = !!uid?.length ? `${base}?uid=${uid}` : `${base}?name=${name}`;
        return this.createClient(login).get(url);
    }
    async postWebcamTest(login, uid, name) {
        const base = `server/webcams/test`;
        const url = !!uid?.length ? `${base}?uid=${uid}` : `${base}?name=${name}`;
        return this.createClient(login).get(url);
    }
    async getNotifierList(login) {
        return this.createClient(login).get(`server/notifiers/list`);
    }
    async postMachineUpdateStatus(login) {
        return this.createClient(login).post(`machine/update/status`);
    }
    async postMachineUpdateRefresh(login, name) {
        const base = `machine/update/refresh`;
        const url = !!name ? `${base}` : `${base}?name=${name}`;
        return this.createClient(login).post(url);
    }
    async postMachineUpdateFull(login) {
        return this.createClient(login).post(`machine/update/full`);
    }
    async postMachineUpdateMoonraker(login) {
        return this.createClient(login).post(`machine/update/moonraker`);
    }
    async postMachineUpdateKlipper(login) {
        return this.createClient(login).post(`machine/update/klipper`);
    }
    async postMachineUpdateClient(login, name) {
        return this.createClient(login).post(`machine/update/client?name=${name}`);
    }
    async postMachineUpdateSystem(login) {
        return this.createClient(login).post(`machine/update/system`);
    }
    async postMachineUpdateRecover(login, name, hard = false) {
        return this.createClient(login).post(`machine/update/recover?name=${name}&hard=${hard}`);
    }
    async postMachineUpdateRollback(login, name) {
        return this.createClient(login).post(`machine/update/rollback?name=${name}`);
    }
    async getMachineDevicePowerDevices(login) {
        return this.createClient(login).get(`machine/device_power/devices`);
    }
    async getMachineDevicePowerDeviceState(login, device) {
        return this.createClient(login).get(`machine/device_power/device?device=${device}`);
    }
    async postMachineDevicePowerDeviceState(login, device, action) {
        return this.createClient(login).post(`machine/device_power/device?device=${device}&action=${action}`);
    }
    async getMachineDevicePowerBatchDeviceState(login, devices) {
        return this.createClient(login).get(`machine/device_power/status?${devices.join("&")}`);
    }
    async postMachineDevicePowerBatchPowerOn(login, device) {
        return this.createClient(login).post(`machine/device_power/on?device=${device}`);
    }
    async postMachineDevicePowerBatchPowerOff(login, device) {
        return this.createClient(login).post(`machine/device_power/off?device=${device}`);
    }
    async getMachineWledStrips(login) {
        return this.createClient(login).get(`machine/wled/strips`);
    }
    async getMachineWledStatuses(login, strips) {
        return this.createClient(login).get(`machine/wled/status?${strips.join("&")}`);
    }
    async postMachineWledPowerOn(login, strips) {
        return this.createClient(login).post(`machine/wled/on?${strips.join("&")}`);
    }
    async postMachineWledPowerOff(login, strips) {
        return this.createClient(login).post(`machine/wled/off?${strips.join("&")}`);
    }
    async postMachineWledPowerStripAction(login, strips) {
        return this.createClient(login).post(`machine/wled/toggle?${strips.join("&")}`);
    }
    async getMachineWledStripAction(login, strip, action, controlParams) {
        const queryParams = Object.entries(controlParams).map(([k, v])=>`${k}=${v}`).join("&");
        return this.createClient(login).get(`machine/wled/strip?strip=${strip}&action=${action}&${queryParams}`);
    }
    async getServerSensorsList(login) {
        return this.createClient(login).get(`server/sensors/list`);
    }
    async getServerSensorItem(login, sensor) {
        return this.createClient(login).get(`server/sensors/info?sensor=${sensor}`);
    }
    async getServerSensorMeasurements(login, sensor) {
        return this.createClient(login).get(`server/sensors/measurements?sensor=${sensor}`);
    }
    async getServerSensorMeasurementsBatch(login) {
        return this.createClient(login).get(`server/sensors/measurements`);
    }
    async getServerSpoolmanStatus(login) {
        return this.createClient(login).get(`server/spoolman/status`);
    }
    async postServerSpoolmanActiveSpool(login, spoolId) {
        return this.createClient(login).post(`server/spoolman/spool_id`, {
            spool_id: spoolId
        });
    }
    async getServerSpoolmanActiveSpool(login) {
        return this.createClient(login).get(`server/spoolman/spool_id`);
    }
    async postServerSpoolmanProxyRequest(login, body) {
        return this.createClient(login).post(`server/spoolman/proxy`, body);
    }
    async getApiVersion(login) {
        return this.createClient(login).get(`api/version`);
    }
    async getServerVersion(login) {
        return this.createClient(login).get(`api/server`);
    }
    async getApiLogin(login) {
        return this.createClient(login).get(`api/login`);
    }
    async getApiSettings(login) {
        return this.createClient(login).get(`api/settings`);
    }
    async getApiJob(login) {
        return this.createClient(login).get(`api/job`);
    }
    async getApiPrinter(login) {
        return this.createClient(login).get(`api/printer`);
    }
    async postApiPrinterCommand(login, commands) {
        return this.createClient(login).post(`api/command`, {
            commands
        });
    }
    async getApiProfiles(login) {
        return this.createClient(login).get(`api/printerprofiles`);
    }
    async getServerHistoryList(login, limit, start, since, before, order = "desc") {
        let params = `limit=${limit}&start=${start}&order=${order}`;
        if (!!before || before === 0) {
            params += "&before=" + before;
        }
        if (!!since || since === 0) {
            params += "&since=" + since;
        }
        return this.createClient(login).get(`server/history/list?${params}`);
    }
    async getServerHistoryTotals(login) {
        return this.createClient(login).get(`server/history/totals`);
    }
    async postServerHistoryResetTotals(login) {
        return this.createClient(login).post(`server/history/reset_totals`);
    }
    async getServerHistoryJob(login, uid) {
        return this.createClient(login).get(`server/history/job?uid=${uid}`);
    }
    async deleteServerHistoryJob(login, uid) {
        const base = `server/history/job`;
        const url = !!uid?.length ? `${base}?uid=${uid}` : `${base}?all=true`;
        return this.createClient(login).get(url);
    }
    convertToQueryString(query) {
        return Object.entries(query).reduce((acc, [key, value])=>{
            if (value.length > 0) {
                acc.push(`${key}=${value.join(",")}`);
            } else {
                acc.push(key);
            }
            return acc;
        }, []).join("&");
    }
    createClient(login, buildFluentOptions) {
        const baseAddress = login.printerURL;
        return this.createAnonymousClient(baseAddress, (o)=>{
            if (buildFluentOptions) {
                buildFluentOptions(o);
            }
        });
    }
    createAnonymousClient(baseAddress, buildFluentOptions) {
        const builder = new _defaulthttpclientbuilder.DefaultHttpClientBuilder();
        return this.httpClientFactory.createClientWithBaseUrl(builder, baseAddress, (b)=>{
            if (buildFluentOptions) {
                buildFluentOptions(b);
            }
        });
    }
}

//# sourceMappingURL=moonraker.client.js.map