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

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