"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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 path = require("path");
const fs = require("fs-extra");
const decorators_1 = require("../decorators");
const Logger_1 = require("../shared/Logger");
const Server_1 = require("../Server");
const realm_sync_server_1 = require("realm-sync-server");
const StatsdExporter_1 = require("../shared/StatsdExporter");
let SyncService = class SyncService {
    constructor(config = {}) {
        this.config = config;
        this.logger = new Logger_1.MuteLogger();
        this.config = config;
        if (!this.config.label) {
            this.config.label = "default";
        }
        this.tags = ["role=master"];
        this.tags.push(`label=${config.label}`);
    }
    setLogger(l) {
        this.logger = l;
    }
    start(server) {
        return __awaiter(this, void 0, void 0, function* () {
            let dataPath = path.join(server.dataPath, "sync");
            if (this.config.dataPath) {
                dataPath = this.config.dataPath;
                this.logger.info("Configuring SyncService with a custom dataPath is deprecated and will be removed in a future version and the value will default to 'sync', relative to the server's dataPath.");
            }
            yield fs.mkdirp(dataPath);
            const config = {
                dataPath,
                publicKeyPath: this.config.publicKeyPath || server.publicKeyPath,
                listenAddress: this.config.listenAddress,
                listenPort: this.config.listenPort,
                featureToken: this.config.featureToken || process.env.SYNC_WORKER_FEATURE_TOKEN,
                logLevel: this.config.logLevel,
                logCallback: (levelNo, message) => {
                    this.logger.log(Logger_1.SyncLogLevel[levelNo], message);
                },
                enableDownloadLogCompaction: this.config.enableDownloadLogCompaction,
                maxDownloadSize: this.config.maxDownloadSize,
            };
            if (this.stats) {
                this.statsdExporter = new StatsdExporter_1.StatsdExporter({ statsSink: this.stats });
                this.statsdSocket = yield this.statsdExporter.startImporter({}, this.logger);
                const address = this.statsdSocket.address();
                config.statsEndpoint = `127.0.0.1:${address.port}`;
            }
            this.syncServer = new realm_sync_server_1.RealmSyncServer(config);
            yield this.syncServer.start();
        });
    }
    stop() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.syncServer) {
                yield this.syncServer.stop();
            }
            if (this.statsdSocket) {
                yield new Promise((resolve) => this.statsdSocket.close(resolve)).catch();
                delete this.statsdSocket;
            }
        });
    }
    address() {
        if (this.syncServer) {
            return this.syncServer.address();
        }
    }
};
__decorate([
    decorators_1.Unmute(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Logger_1.Logger]),
    __metadata("design:returntype", void 0)
], SyncService.prototype, "setLogger", null);
__decorate([
    decorators_1.Start(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Server_1.Server]),
    __metadata("design:returntype", Promise)
], SyncService.prototype, "start", null);
__decorate([
    decorators_1.Stop(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], SyncService.prototype, "stop", null);
__decorate([
    decorators_1.Address(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], SyncService.prototype, "address", null);
SyncService = __decorate([
    decorators_1.ServiceName('sync'),
    __metadata("design:paramtypes", [Object])
], SyncService);
exports.SyncService = SyncService;
//# sourceMappingURL=SyncService.js.map