"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BinaryToBufferTask = void 0;
const path_1 = __importDefault(require("path"));
const ExifToolTask_1 = require("./ExifToolTask");
const FilenameCharsetArgs_1 = require("./FilenameCharsetArgs");
const String_1 = require("./String");
/**
 * Task that returns an error string (to prevent retries), or undefined if
 * everything seems to have worked.
 */
class BinaryToBufferTask extends ExifToolTask_1.ExifToolTask {
    constructor(tagname, args) {
        super(args);
        this.tagname = tagname;
    }
    static for(tagname, imgSrc) {
        // NOTE TO FUTURE ME: we don't need to escape these arguments, because
        // ExifTool separates them via newlines.
        const args = [
            ...FilenameCharsetArgs_1.Utf8FilenameCharsetArgs,
            "-json",
            "-b",
            "-" + tagname,
            path_1.default.resolve(imgSrc),
        ];
        return new BinaryToBufferTask(tagname, args);
    }
    parse(data, err) {
        var _a;
        try {
            const obj = (_a = JSON.parse(data)) === null || _a === void 0 ? void 0 : _a[0];
            // did they get the casing right?
            {
                const result = decode(obj[this.tagname]);
                if (result != null)
                    return result;
            } // hmm, incorrect casing. Check the other keys.
            for (const k of Object.keys(obj)) {
                if (k.toLowerCase() === this.tagname.toLowerCase()) {
                    const result = decode(obj[k]);
                    if (result != null)
                        return result;
                }
            }
        }
        catch (caught) {
            err !== null && err !== void 0 ? err : (err = (0, String_1.notBlank)(data)
                ? new Error(data)
                : caught instanceof Error
                    ? caught
                    : new Error(String(caught)));
        }
        return err !== null && err !== void 0 ? err : new Error(this.tagname + " not found");
    }
}
exports.BinaryToBufferTask = BinaryToBufferTask;
const B64Prefix = "base64:";
function decode(data) {
    return data == null || !data.startsWith(B64Prefix)
        ? undefined
        : Buffer.from(data.substring(B64Prefix.length), "base64");
}
//# sourceMappingURL=BinaryToBufferTask.js.map