"use strict";
/**
 * Copyright © 2018 Emu Analytics
 */
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const debounce = require("debounce-promise");
const utils_1 = require("../utils");
exports.app = express();
exports.app.use(bodyParser.json({ limit: '1mb' }));
exports.app.use(express.static(path.join(__dirname, '../../maputnik')));
exports.app.get('/styles', (req, res) => {
    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');
        utils_1.logInfo(`Loading style '${style.id}'`);
        res.json(style);
    }
    catch (e) {
        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) {
        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 = debounce(saveStyleInternal, 2000, { leading: true });
//# sourceMappingURL=app.js.map