"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 library_cleaner_1 = require("./library-cleaner");
const compactd_models_1 = require("compactd-models");
const fs = require("fs");
const Scanner_1 = require("../scanner/Scanner");
const files = new database_1.default('files');
function deleteLibraryTree(libraryId) {
    return new Promise((resolve, reject) => {
        const scanner = new Scanner_1.Scanner(libraryId);
        fs.unlink(scanner.treePath, (err) => {
            // if (err) return reject(err);
            resolve();
        });
    });
}
function resetLibrary(libraryId) {
    return __awaiter(this, void 0, void 0, function* () {
        const res = yield files.query('files/by_library', {
            startkey: libraryId,
            endkey: libraryId,
            include_docs: true
        });
        yield Promise.all(res.rows.map(({ doc }) => {
            return files.remove(doc._id, doc._rev);
        }));
        yield library_cleaner_1.default(database_1.default, false);
        yield deleteLibraryTree(libraryId);
    });
}
exports.resetLibrary = resetLibrary;
const emit = Function();
function createViews() {
    return __awaiter(this, void 0, void 0, function* () {
        const ddoc = {
            _id: '_design/files',
            views: {
                by_library: {
                    map: function (doc) {
                        emit(doc.library);
                    }.toString()
                }
            }
        };
        yield files.put(ddoc);
    });
}
exports.createViews = createViews;
function toggleHideTrack(trackID) {
    return __awaiter(this, void 0, void 0, function* () {
        const Track = new database_1.default('tracks');
        const track = yield Track.get(trackID);
        yield Track.put({
            _id: track._id,
            _rev: track._rev,
            name: track.name,
            artist: track.artist,
            album: track.album,
            number: track.number,
            duration: track.duration,
            disc: track.disc,
            hidden: !track.hidden,
        });
    });
}
exports.toggleHideTrack = toggleHideTrack;
function getRemoveToken(trackID) {
    return __awaiter(this, void 0, void 0, function* () {
    });
}
exports.getRemoveToken = getRemoveToken;
function removeTrack(trackID) {
    return __awaiter(this, void 0, void 0, function* () {
        const Track = new database_1.default('tracks');
        const track = yield Track.get(trackID);
        yield Track.remove(track._id, track._rev);
        yield library_cleaner_1.default(database_1.default);
    });
}
exports.removeTrack = removeTrack;
function changeTrackArtist(trackId, artistId) {
    return __awaiter(this, void 0, void 0, function* () {
        const Track = new database_1.default('tracks');
        const Artist = new database_1.default('artists');
        const Album = new database_1.default('albums');
        const File = new database_1.default('files');
        const artist = yield Artist.get(artistId);
        const track = yield Track.get(trackId);
        if (track.artist === artist._id) {
            return;
        }
        const albumProps = {
            artist: artist._id,
            name: compactd_models_1.albumURI(track.album).name,
        };
        const props = Object.assign({}, albumProps, { album: compactd_models_1.albumURI(compactd_models_1.mapAlbumToParams(albumProps)), number: track.number, name: track.name });
        const newTrack = Object.assign({}, props, { hidden: track.hidden, duration: track.duration, disc: track.disc, _id: compactd_models_1.trackURI(compactd_models_1.mapTrackToParams(props)) });
        yield Track.remove(track._id, track._rev);
        yield Track.put(newTrack);
        // if the album doesnt exist we create it
        const originalAlbum = yield Album.get(track.album);
        try {
            const album = yield Album.get(newTrack.album);
        }
        catch (err) {
            const albumProps = {
                artist: newTrack.artist,
                name: originalAlbum.name,
                dateAdded: Date.now()
            };
            const album = Object.assign({ _id: compactd_models_1.albumURI(compactd_models_1.mapAlbumToParams(albumProps)) }, albumProps);
            yield Album.put(album);
        }
        // Move the files so we can still listen to the music
        const files = yield File.allDocs({
            startkey: trackId,
            endkey: trackId + '\uffff',
            include_docs: true
        });
        yield Promise.all(files.rows.map(({ doc: file }) => __awaiter(this, void 0, void 0, function* () {
            const props = {
                artist: artist._id,
                album: track.album,
                name: track.name,
                number: '' + track.number,
                track: newTrack._id,
                bitrate: '' + file.bitrate,
                hash: '',
                path: file.path
            };
            const newFile = Object.assign({}, props, { _id: compactd_models_1.fileURI(compactd_models_1.mapFileToParams(props)), library: file.library, duration: file.duration, format: file.format, path: file.path });
            yield File.remove(file._id, file._rev);
            yield File.put(newFile);
        })));
        yield library_cleaner_1.default(database_1.default);
    });
}
exports.changeTrackArtist = changeTrackArtist;
//# sourceMappingURL=library-utils.js.map