"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const promises_1 = __importDefault(require("fs/promises"));
const jimp_1 = __importDefault(require("jimp"));
const crypto_1 = __importDefault(require("crypto"));
const app = (0, express_1.default)();
app.use('/assets', express_1.default.static('images'));
/* eslint-disable max-depth */
/* eslint-disable complexity */
app.listen(3000, () => {
    console.log('The application is listening on port 3000!');
});
/**
 *
 *
 * @param path the folder to search
 *
 * @return the list of files included in this folder/subfolders
 */
function filesList(Path) {
    var _a, e_1, _b, _c;
    return __awaiter(this, void 0, void 0, function* () {
        const files = [];
        const subFolders = yield promises_1.default.readdir(Path);
        try {
            for (var _d = true, subFolders_1 = __asyncValues(subFolders), subFolders_1_1; subFolders_1_1 = yield subFolders_1.next(), _a = subFolders_1_1.done, !_a;) {
                _c = subFolders_1_1.value;
                _d = false;
                try {
                    const subFolder = _c;
                    const stats = yield promises_1.default.stat(Path + '/' + subFolder);
                    if (stats.isDirectory()) {
                        files.push(...yield filesList(Path + '/' + subFolder));
                    }
                    else {
                        files.push(Path + '/' + subFolder);
                    }
                }
                finally {
                    _d = true;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_d && !_a && (_b = subFolders_1.return)) yield _b.call(subFolders_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return files;
    });
}
app.get('/program', (_req, res) => {
    ((dirPath) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, e_2, _b, _c;
        const files = yield filesList(dirPath);
        console.log(files);
        // Filtre
        const data = (yield promises_1.default.readFile('./output.json')).toString('utf8');
        let json = {};
        try {
            json = JSON.parse(data);
        }
        catch (_d) {
            console.log('handeling...');
        }
        try {
            for (var _e = true, files_1 = __asyncValues(files), files_1_1; files_1_1 = yield files_1.next(), _a = files_1_1.done, !_a;) {
                _c = files_1_1.value;
                _e = false;
                try {
                    const file = _c;
                    const bFile = path_1.default.basename(file);
                    const pName = path_1.default.dirname(file);
                    const hash = crypto_1.default.createHash('sha256');
                    hash.setEncoding('hex');
                    const readI = yield promises_1.default.readFile(`${file}`);
                    hash.write(readI);
                    hash.end();
                    const sha256sum = hash.read();
                    console.log('bfile = ' + bFile);
                    if (bFile.startsWith('.')) {
                        continue;
                    }
                    else if (json[file] === sha256sum) {
                        console.log('This picture has already been turned to sepia');
                        continue;
                    }
                    // Modification des données
                    json[file] = sha256sum;
                    // Ré-écriture dans le fichier output
                    yield promises_1.default.writeFile('output.json', JSON.stringify(json));
                    try {
                        const image = yield jimp_1.default.read(readI);
                        image.sepia();
                        console.log(bFile);
                        const newFileName = pName + '/.' + bFile;
                        console.log('newfilename:' + newFileName);
                        // save image with new file name
                        yield image.writeAsync(`${newFileName}`);
                        console.log('Images have been inverted and rename ' + '.' + file);
                    }
                    catch (err) {
                        console.log('this file is not an image');
                    }
                }
                finally {
                    _e = true;
                }
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (!_e && !_a && (_b = files_1.return)) yield _b.call(files_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
        res.send('Pictures transformed');
        res.end();
    }))('./images');
});
{
    app.get('/', (_req, res) => __awaiter(void 0, void 0, void 0, function* () {
        const list = yield filesList('./content');
        const item = list[Math.floor(Math.random() * ((list)).length)];
        const itemB = yield promises_1.default.readFile(item);
        res.send(itemB);
        console.log(item);
    }));
}
