"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteFile = exports.updateFile = exports.readFile = exports.readFiles = exports.createFile = void 0;
const ItemsService = __importStar(require("./items"));
const storage_1 = __importDefault(require("../storage"));
const database_1 = __importDefault(require("../database"));
const logger_1 = __importDefault(require("../logger"));
const sharp_1 = __importDefault(require("sharp"));
const icc_1 = require("icc");
const exif_reader_1 = __importDefault(require("exif-reader"));
const parse_iptc_1 = __importDefault(require("../utils/parse-iptc"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
exports.createFile = (data, stream, accountability) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const id = uuid_1.v4();
    const payload = Object.assign(Object.assign({}, data), { id });
    payload.filename_disk = payload.id + path_1.default.extname(payload.filename_disk);
    const pipeline = sharp_1.default();
    if ((_a = payload.type) === null || _a === void 0 ? void 0 : _a.startsWith('image')) {
        pipeline.metadata().then((meta) => {
            payload.width = meta.width;
            payload.height = meta.height;
            payload.filesize = meta.size;
            payload.metadata = {};
            if (meta.icc) {
                payload.metadata.icc = icc_1.parse(meta.icc);
            }
            if (meta.exif) {
                payload.metadata.exif = exif_reader_1.default(meta.exif);
            }
            if (meta.iptc) {
                payload.metadata.iptc = parse_iptc_1.default(meta.iptc);
                payload.title = payload.title || payload.metadata.iptc.headline;
                payload.description = payload.description || payload.metadata.iptc.caption;
            }
        });
    }
    const pk = yield ItemsService.createItem('directus_files', payload, accountability);
    yield storage_1.default.disk(data.storage).put(payload.filename_disk, stream.pipe(pipeline));
    return pk;
});
exports.readFiles = (query, accountability) => __awaiter(void 0, void 0, void 0, function* () {
    return yield ItemsService.readItems('directus_files', query, accountability);
});
exports.readFile = (pk, query, accountability) => __awaiter(void 0, void 0, void 0, function* () {
    return yield ItemsService.readItem('directus_files', pk, query, accountability);
});
exports.updateFile = (pk, data, accountability, stream) => __awaiter(void 0, void 0, void 0, function* () {
    /**
     * @TODO
     * Handle changes in storage adapter -> going from local to S3 needs to delete from one, upload to the other
     */
    /**
     * @TODO
     * Extract metadata here too
     */
    if (stream) {
        const file = yield database_1.default
            .select('storage', 'filename_disk')
            .from('directus_files')
            .where({ id: pk })
            .first();
        yield storage_1.default.disk(file.storage).put(file.filename_disk, stream);
    }
    return yield ItemsService.updateItem('directus_files', pk, data, accountability);
});
exports.deleteFile = (pk, accountability) => __awaiter(void 0, void 0, void 0, function* () {
    /** @todo use ItemsService */
    const file = yield database_1.default
        .select('storage', 'filename_disk')
        .from('directus_files')
        .where({ id: pk })
        .first();
    const { wasDeleted } = yield storage_1.default.disk(file.storage).delete(file.filename_disk);
    logger_1.default.info(`File ${file.filename_download} deleted: ${wasDeleted}`);
    yield database_1.default.delete().from('directus_files').where({ id: pk });
});
