"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 node_path_1 = __importDefault(require("node: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 {
    tagname;
    constructor(tagname, args, options) {
        super(args, options);
        this.tagname = tagname;
    }
    static for(tagname, imgSrc, options) {
        // 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];
        args.push(node_path_1.default.resolve(imgSrc));
        return new BinaryToBufferTask(tagname, args, options);
    }
    parse(data, err) {
        try {
            const obj = JSON.parse(data)?.[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 ??= (0, String_1.notBlank)(data)
                ? new Error(data)
                : caught instanceof Error
                    ? caught
                    : new Error(String(caught));
        }
        return err ?? new Error(this.tagname + " not found");
    }
}
exports.BinaryToBufferTask = BinaryToBufferTask;
const B64Prefix = "base64:";
function decode(data) {
    return !data?.startsWith(B64Prefix)
        ? undefined
        : Buffer.from(data.substring(B64Prefix.length), "base64");
}
//# sourceMappingURL=BinaryToBufferTask.js.map