'use strict';

const config = require('config');
const path = require('path');
const fs = require('fs-extra');
const moment = require('moment');

const argv = require('../argv');
const knex = require('../knex');

async function init() {
    const posters = await knex('actors')
        .select('actors.name as actor_name', 'releases.title', 'releases.date', 'media.path', 'sites.name as site_name', 'networks.name as network_name')
        .whereIn('actors.name', argv.actors)
        .join('releases_actors', 'releases_actors.actor_id', 'actors.id')
        .join('releases', 'releases_actors.release_id', 'releases.id')
        .join('releases_posters', 'releases_posters.release_id', 'releases.id')
        .join('sites', 'sites.id', 'releases.site_id')
        .join('networks', 'networks.id', 'sites.network_id')
        .join('media', 'releases_posters.media_id', 'media.id');

    await Promise.all(posters.map(async (poster) => {
        const source = path.join(config.media.path, poster.path);
        const target = path.join(config.media.path, 'posters', `${poster.actor_name} - ${poster.network_name}: ${poster.site_name} - ${poster.title.replace(/[/.]/g, '_')} (${moment.utc(poster.date).format('YYYY-MM-DD')}).jpeg`);

        const file = await fs.readFile(source);
        await fs.writeFile(target, file);

        return file;
    }));

    knex.destroy();
}

init();
