'use strict';

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

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

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

async function init() {
    const posters = await knex('actors')
        .select('actors.name', 'releases.title', 'media.path')
        .whereIn('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('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.title.replace('/', '_')}.${poster.name}.jpeg`);

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

        return file;
    }));
}

init();
