
const path = require('path');
const { AutotagModel, AUTOTAG_TYPE } = require("../model/autotag.js");
const MediaFileModel = require('../model/mediaItem.js').MediaFileModel;
const MediaFileTagModel = require('../model/mediaItemTag.js').MediaFileTagModel;

class AutoTagBuilder
{
    #initialized = false;
    #loading = false;
    #pathTags = [];
    #metaTags = [];

    constructor()
    {
    }

    #normalizePath(p) {
        p = path.normalize(p);
        if (!p.endsWith('/'))
            p = p + '/';
        return p;
    }

    async reloadRules(app) {
        this.#pathTags = [];
        this.#metaTags = [];

        for (let proto of await app.databaseHelper.fetch(AutotagModel)) {
            switch (proto.type) {
                case AUTOTAG_TYPE.path:
                    this.#pathTags.push({ path: this.#normalizePath(proto.typeData), tag: proto.tag }); break;
                case AUTOTAG_TYPE.meta:
                    this.#metaTags.push({ meta: proto.typeData, tag: proto.tag }); break;
            }
        }
        this.#initialized = true;
    }

    async rebuildPathTags(app) {
        if (this.#loading)
            return;
        this.#loading = true;
        if (!this.#initialized)
            await this.reloadRules(app);
        await app.databaseHelper.remove(MediaFileTagModel, { fromAutotag: true });
        let entities = [];
        for (let proto of this.#pathTags) {
            for (let matchingFiles of await app.databaseHelper.runSql("select * from `"+MediaFileModel.prototype.getTableName.call(null) +"` where path like '" +proto.path +"%'")) {
                let entity = new MediaFileTagModel(matchingFiles.fixedSum, proto.tag, false, true);
                entities.push(entity);
                if (entities.length >= 100) {
                    await app.databaseHelper.insertMultipleSameTable(entities);
                    entities = [];
                }
            }
        }
        await app.databaseHelper.insertMultipleSameTable(entities);
        this.#loading = false;
        console.log("Done processing autotags");
    }
}

module.exports = new AutoTagBuilder();

