"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 datasource_1 = require("../datasource");
const database_1 = require("../../database");
const sharp = require("sharp");
const mime = require("mime");
const config_1 = require("../../config");
const md5 = require("md5");
const storyboard_1 = require("storyboard");
function reset() {
    return __awaiter(this, void 0, void 0, function* () {
        const artworks = new database_1.default("artworks");
        yield artworks.destroy({});
    });
}
exports.reset = reset;
function saveToFile(promise, id) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!promise)
            return;
        const buffer = yield promise;
        if (!buffer)
            return;
        try {
            const image = sharp(buffer);
            const metadata = yield image.metadata();
            const mimeType = mime.getType(metadata.format);
            storyboard_1.mainStory.info('aquarelle', `Saving artwork for ${id} (width=${metadata.width}, mime=${mimeType})`);
            const artworks = new database_1.default('artworks');
            const docId = 'artworks/' + id;
            const smallImage = yield image.resize(64).toBuffer();
            yield artworks.put({
                _id: docId,
                owner: id,
                date: Date.now(),
                _attachments: {
                    'large': {
                        content_type: mimeType,
                        data: buffer,
                        digest: 'md5-' + md5(buffer)
                    },
                    'small': {
                        content_type: mimeType,
                        data: smallImage,
                        digest: 'md5-' + md5(smallImage)
                    }
                }
            });
        }
        catch (err) {
            if (err.status === 409)
                return;
            storyboard_1.mainStory.warn('aquarelle', 'Could not save artwork for ' + id, { attach: err });
        }
    });
}
function processAlbums(onFetchAlbum = new Function()) {
    return __awaiter(this, void 0, void 0, function* () {
        const albums = new database_1.default('albums');
        const artists = new database_1.default('artists');
        const source = new datasource_1.MediaSource(config_1.default.get('datasourceKey'));
        yield Promise.all((yield albums.allDocs({ include_docs: true }))
            .rows.map(({ doc }) => __awaiter(this, void 0, void 0, function* () {
            // if (fs.existsSync(getCacheEntry(doc._id)) && !replace) return;
            const artist = yield artists.get(doc.artist);
            onFetchAlbum(doc.name);
            yield saveToFile(source.getAlbumCover(artist.name, doc.name), doc._id);
        })));
    });
}
exports.processAlbums = processAlbums;
function processArtists(onFetchArtist = new Function()) {
    return __awaiter(this, void 0, void 0, function* () {
        const artists = new database_1.default('artists');
        const source = new datasource_1.MediaSource(config_1.default.get('datasourceKey'));
        yield Promise.all((yield artists.allDocs({ include_docs: true }))
            .rows.map(({ doc }) => __awaiter(this, void 0, void 0, function* () {
            // if (fs.existsSync(getCacheEntry(doc._id)) && !replace) return;
            onFetchArtist(doc.name);
            try {
                yield saveToFile(source.getArtistArtwork(doc.name), doc._id);
            }
            catch (err) {
                console.log(err);
                return;
            }
        })));
    });
}
exports.processArtists = processArtists;
//# sourceMappingURL=AquarelleAgent.js.map