"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const nativescript_preview_sdk_1 = require("nativescript-preview-sdk");
const events_1 = require("events");
const preview_app_constants_1 = require("./preview-app-constants");
const pako = require("pako");
class PreviewSdkService extends events_1.EventEmitter {
    constructor($errors, $logger, $httpClient, $config) {
        super();
        this.$errors = $errors;
        this.$logger = $logger;
        this.$httpClient = $httpClient;
        this.$config = $config;
        this.messagingService = null;
        this.instanceId = null;
        this.connectedDevices = [];
    }
    get qrCodeUrl() {
        return `nsplay://boot?instanceId=${this.instanceId}&pKey=${preview_app_constants_1.PubnubKeys.PUBLISH_KEY}&sKey=${preview_app_constants_1.PubnubKeys.SUBSCRIBE_KEY}&template=play-ng`;
    }
    initialize() {
        const initConfig = this.getInitConfig();
        this.messagingService = new nativescript_preview_sdk_1.MessagingService();
        this.instanceId = this.messagingService.initialize(initConfig);
    }
    applyChanges(files, platform) {
        return new Promise((resolve, reject) => {
            this.messagingService.applyChanges(this.instanceId, { files, platform }, err => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve();
                }
            });
        });
    }
    stop() {
        this.messagingService.stop();
    }
    getInitConfig() {
        return {
            pubnubPublishKey: preview_app_constants_1.PubnubKeys.PUBLISH_KEY,
            pubnubSubscribeKey: preview_app_constants_1.PubnubKeys.SUBSCRIBE_KEY,
            callbacks: this.getCallbacks(),
            getInitialFiles: () => __awaiter(this, void 0, void 0, function* () {
                return {
                    files: []
                };
            })
        };
    }
    getCallbacks() {
        return {
            onLogSdkMessage: (log) => {
                this.$logger.trace("Received onLogSdkMessage message: ", log);
            },
            onConnectedDevicesChange: (connectedDevices) => ({}),
            onLogMessage: (log, deviceName) => {
                this.$logger.info(`LOG from device ${deviceName}: ${log}`);
            },
            onRestartMessage: () => {
                this.$logger.trace("Received onRestartMessage event.");
            },
            onUncaughtErrorMessage: () => {
                this.$errors.failWithoutHelp("Error while communicating with preview app.");
            },
            onDeviceConnectedMessage: (deviceConnectedMessage) => ({}),
            onDeviceConnected: (device) => {
                this.emit(preview_app_constants_1.PreviewSdkEventNames.DEVICE_CONNECTED, device);
                if (!_.includes(this.connectedDevices, device)) {
                    this.connectedDevices.push(device);
                }
            },
            onDevicesPresence: (devices) => ({}),
            onSendingChange: (sending) => ({}),
            onBiggerFilesUpload: (filesContent, callback) => __awaiter(this, void 0, void 0, function* () {
                const gzippedContent = Buffer.from(pako.gzip(filesContent));
                const playgroundUploadResponse = yield this.$httpClient.httpRequest({
                    url: this.$config.UPLOAD_PLAYGROUND_FILES_ENDPOINT,
                    method: "POST",
                    body: gzippedContent,
                    headers: {
                        "Content-Encoding": "gzip",
                        "Content-Type": "text/plain"
                    }
                });
                const responseBody = JSON.parse(playgroundUploadResponse.body);
                const location = responseBody && responseBody.location;
                callback(location, playgroundUploadResponse.error);
            })
        };
    }
}
exports.PreviewSdkService = PreviewSdkService;
$injector.register("previewSdkService", PreviewSdkService);
