"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 database_1 = require("../../database");
const docuri = require('docuri');
exports.Route = docuri.route('reports/:type/:ts');
const reports = new database_1.default('reports');
function report(type, track) {
    return __awaiter(this, void 0, void 0, function* () {
        const ts = Date.now();
        const doc = yield reports.put({
            track: track, type, ts, _id: exports.Route({ type, ts })
        });
        return doc;
    });
}
exports.report = report;
function getTopTracks(limit = 10) {
    return __awaiter(this, void 0, void 0, function* () {
        const res = yield reports.query('analytics/by_track', {
            group: true,
            reduce: true
        });
        return res.rows.sort((a, b) => {
            return b.value - a.value;
        }).filter((key, index) => index < limit);
    });
}
exports.getTopTracks = getTopTracks;
// This is just to pass
const emit = null;
function initialize() {
    return __awaiter(this, void 0, void 0, function* () {
        const ddoc = {
            _id: '_design/analytics',
            views: {
                by_track: {
                    reduce: '_count',
                    map: function (doc) {
                        emit(doc.track, doc.ts);
                    }.toString()
                }
            }
        };
        yield reports.put(ddoc);
    });
}
exports.initialize = initialize;
//# sourceMappingURL=Analytics.js.map