"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 fs = require("fs-extra");
const config_1 = require("../../config");
const sha1 = require("sha1");
const mkdirp = require("mkdirp");
const path = require("path");
const qs = require("qs");
const child_process_1 = require("child_process");
const WaveformData = require('waveform-data');
const hashCash = {};
function waveformCLI(mediaFile, imageFile) {
    return `audiowaveform -i "${mediaFile.replace('"', '\\"')}" -b 8 -z 256 -o "${imageFile}"`;
}
function generateWaveform(mediaFile, imagePath) {
    return new Promise((resolve, reject) => {
        child_process_1.exec(waveformCLI(mediaFile, imagePath), function (error, stdout, stderr) {
            if (error) {
                return reject(error);
            }
            resolve(error);
        });
    });
}
function processFile(file) {
    return __awaiter(this, void 0, void 0, function* () {
        yield generateWaveform(file, getCacheEntry(file));
        return fs.readFile(getCacheEntry(file));
    });
}
function getCacheEntry(file) {
    const id = file + '?' + qs.stringify({});
    const hash = hashCash[id] ? hashCash[id] : sha1(id);
    return path.join(getCacheDir(), hash + '.dat');
}
function getData(id) {
    return __awaiter(this, void 0, void 0, function* () {
        const file = yield getFileFromTrack(id);
        const cache = getCacheEntry(file.path);
        if (yield fs.pathExists(cache)) {
            return fs.readFile(cache);
        }
        const data = processFile(file.path);
        return data;
    });
}
exports.default = {
    getData
};
function getFileFromTrack(id) {
    return __awaiter(this, void 0, void 0, function* () {
        const files = new database_1.default('files');
        const docs = yield files.allDocs({
            include_docs: true,
            startkey: id,
            endkey: id + '\uffff'
        });
        const file = docs.rows[0].doc;
        return file;
    });
}
function getCacheDir() {
    return path.join(config_1.default.get('dataDirectory'), 'waveforms');
}
mkdirp.sync(getCacheDir());
//# sourceMappingURL=Waveform.js.map