"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.app = void 0;
const express_1 = __importDefault(require("express"));
const path = __importStar(require("path"));
const bodyParser = __importStar(require("body-parser"));
const debounce_promise_1 = __importDefault(require("debounce-promise"));
const utils_1 = require("../utils");
exports.app = (0, express_1.default)();
exports.app.use(bodyParser.json({ limit: '1mb' }));
exports.app.use(express_1.default.static(path.join(__dirname, '../../maputnik')));
exports.app.get('/styles', (req, res) => {
    (0, utils_1.logInfo)(':thumbsup: Maputnik connected');
    const style = exports.app.get('style');
    res.json([style.id]);
});
exports.app.get('/styles/:id', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const style = exports.app.get('style');
        const client = exports.app.get('client');
        (0, utils_1.logInfo)(`Loading style '${style.id}'`);
        res.json(style);
    }
    catch (e) {
        (0, utils_1.logError)(e.message);
    }
}));
exports.app.put('/styles/:id', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const client = exports.app.get('client');
        // Ensure style is set on app in case user reloads browser
        exports.app.set('style', req.body);
        // Ignore saves if not writeable
        if (!exports.app.get('writeable')) {
            return res.status(204).send();
        }
        const modifiedStyle = Object.assign({}, req.body);
        modifiedStyle.sources = relativeTileSources(modifiedStyle.sources, `${client.baseUrl}`);
        modifiedStyle.glyphs = relativeURL(modifiedStyle.glyphs, client.baseUrl);
        modifiedStyle.sprite = relativeURL(modifiedStyle.sprite, client.baseUrl);
        yield saveStyle(client, modifiedStyle.id, modifiedStyle);
        res.status(204).send();
    }
    catch (e) {
        (0, utils_1.logError)(e.message);
    }
}));
function relativeTileSources(sources, baseUrl) {
    return Object.keys(sources).reduce((accum, key) => {
        let source = sources[key];
        if (source.hasOwnProperty('url')) {
            source = Object.assign(Object.assign({}, source), { url: relativeURL(source.url, baseUrl) });
        }
        // For geojson sources
        if (source.hasOwnProperty('data')) {
            source = Object.assign(Object.assign({}, source), { data: relativeURL(source.data, baseUrl) });
        }
        if (source.hasOwnProperty('tiles')) {
            source = Object.assign(Object.assign({}, source), { tiles: source.tiles.map((tileUrl) => relativeURL(tileUrl, baseUrl)) });
        }
        accum[key] = source;
        return accum;
    }, {});
}
/**
 * Expand URLs - add base URL to relative URLs and add any  query parameters not explicitly set in URL
 */
function relativeURL(url, baseUrl) {
    const u = new URL(url, baseUrl);
    u.searchParams.delete('apikey');
    return u
        .toString()
        .replace(baseUrl, '')
        .replace(/%7B/g, '{')
        .replace(/%7D/g, '}');
}
function saveStyleInternal(client, styleId, modifiedStyle) {
    return client.styles.update(styleId, { style: modifiedStyle });
}
const saveStyle = (0, debounce_promise_1.default)(saveStyleInternal, 2000, { leading: true });
//# sourceMappingURL=app.js.map