'use strict';

const async = require('async'),
    fs = require('node:fs'),
    path = require('node:path');

const APPICONS_DIR = '/home/yellowtent/boxdata/appicons';

exports.up = function(db, callback) {
    async.series([
        db.runSql.bind(db, 'ALTER TABLE apps ADD COLUMN icon MEDIUMBLOB'),
        db.runSql.bind(db, 'ALTER TABLE apps ADD COLUMN appStoreIcon MEDIUMBLOB'),
        function migrateIcons(next) {
            fs.readdir(APPICONS_DIR, function (error, filenames) {
                if (error && error.code === 'ENOENT') return next();
                if (error) return next(error);

                async.eachSeries(filenames, function (filename, iteratorCallback) {
                    const icon = fs.readFileSync(path.join(APPICONS_DIR, filename));
                    const appId = filename.split('.')[0];

                    if (filename.endsWith('.user.png')) {
                        db.runSql('UPDATE apps SET icon=? WHERE id=?', [ icon, appId ], iteratorCallback);
                    } else {
                        db.runSql('UPDATE apps SET appStoreIcon=? WHERE id=?', [ icon, appId ], iteratorCallback);
                    }
                }, function (error) {
                    if (error) return next(error);

                    fs.rm(APPICONS_DIR, { recursive: true }, next);
                });
            });
        }
    ], callback);
};

exports.down = function(db, callback) {
    async.series([
        db.runSql.bind(db, 'ALTER TABLE apps DROP COLUMN icon'),
        db.runSql.bind(db, 'ALTER TABLE apps DROP COLUMN appStoreIcon'),
    ], callback);
};
