"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Exception = void 0;
const image_magick_1 = require("../image-magick");
const exception_severity_1 = require("./exception-severity");
const pointer_1 = require("../pointer/pointer");
const string_1 = require("../native/string");
class Exception {
    constructor(pointer) {
        this.pointer = pointer;
    }
    get ptr() { return this.pointer.ptr; }
    check(success, error) {
        if (Exception.isRaised(this.pointer) && Exception.isErrorSeverity(this.pointer))
            return error();
        return success();
    }
    static usePointer(func) {
        return pointer_1.Pointer.use((pointer) => {
            const result = func(pointer.ptr);
            return Exception.checkException(pointer, result);
        });
    }
    static use(func) {
        return pointer_1.Pointer.use((pointer) => {
            const result = func(new Exception(pointer));
            return Exception.checkException(pointer, result);
        });
    }
    static checkException(exception, result) {
        if (!Exception.isRaised(exception))
            return result;
        if (Exception.isErrorSeverity(exception))
            Exception.throw(exception);
        else
            Exception.dispose(exception);
        return result;
    }
    static isErrorSeverity(exception) {
        const severity = image_magick_1.ImageMagick._api._MagickExceptionHelper_Severity(exception.value);
        return severity >= exception_severity_1.ExceptionSeverity.Error;
    }
    static isRaised(exception) {
        return exception.value !== 0;
    }
    static throw(exception) {
        const errorMessage = Exception.getMessage(exception);
        Exception.dispose(exception);
        throw new Error(errorMessage);
    }
    static getMessage(exception) {
        const message = image_magick_1.ImageMagick._api._MagickExceptionHelper_Message(exception.value);
        const description = image_magick_1.ImageMagick._api._MagickExceptionHelper_Description(exception.value);
        let errorMessage = string_1._createString(message, 'Unknown error');
        if (description !== 0) {
            errorMessage += `(${image_magick_1.ImageMagick._api.UTF8ToString(description)})`;
        }
        return errorMessage;
    }
    static dispose(exception) {
        image_magick_1.ImageMagick._api._MagickExceptionHelper_Dispose(exception.value);
    }
}
exports.Exception = Exception;
