#!/bin/node

const CONFIG = require('./src/config.js');
const path = require('path');
const fs = require('fs');
const Router = require('node-simple-router');
const http = require('http');
const Security = require('./src/security.js');
const RouterUtils = require('./src/routerUtils.js').RouterUtils;

const UPDATE_INTERVAL = 1800000; // 30 min

function App() {
    this.router = new Router({ static_route: __dirname+"/static/" });
    this.routerUtils = new RouterUtils(this);
    this.databaseHelper = require('craftlabhttpserver/src/databaseHelper').DatabaseHelper;
    this.libraryManager = require('./src/libraryManager.js').LibraryManager;
}

App.prototype.init = async function() {
    [
        "./router/bootstrap.js",
        "./router/api.js",
        "./router/index.js"
    ].forEach(i => require(i).register(this));

    await this.databaseHelper.init([
        require('./model/session.js').SessionModel,
        require('./model/mediaItem.js').MediaFileModel,
        require('./model/mediaItemMeta.js').MediaFileMetaModel,
        require('./model/mediaItemTag.js').MediaFileTagModel,
        require('./model/access.js').AccessModel,
        require('./model/autotag.js').AutotagModel,
        require('./model/configModel.js').ConfigModel
    ]);
}

App.prototype.run = async function() {
    let BuilderClass = require('./src/autotagBuilder');

    http.createServer(this.router).listen(CONFIG.port);
    await this.libraryManager.updateLibraries(this.databaseHelper);
    await BuilderClass.rebuildPathTags(this);
    setInterval(async () => {
        await this.libraryManager.updateLibraries(this.databaseHelper);
        BuilderClass.rebuildPathTags(this);
    }, UPDATE_INTERVAL);
}

console.info = () => {};
let app = new App();
app.init().then(() => app.run());

