% mibShowErrorDialog function to show an error dialog
%
% Author: Ilya Belevich, University of Helsinki (ilya.belevich @ helsinki.fi)
% Date: 18.12.2023
%
% License: BSD-3 clause (https://opensource.org/license/bsd-3-clause/)

function mibShowErrorDialog(guiHandle, err, winTitle, optionalPrefix, optionalSuffix)
% function mibShowErrorDialog(obj, err, winTitle, optionalPrefix, optionalSuffix)
% show error that is generated in try/catch blocks
%
% Parameters:
% guiHandle: handle to appdesigner window (for example, obj.View.gui)
% err: a structure generated by MATLAB, when an error is
% triggered with the following fields,
%   .identifier - identificator of the error
%   .message - error message
%   .cause - MException
% winTitle: an optional string with a title for the window
% optionalPrefix: an optional text string that will be added before the end of the error message
% optionalSuffix: an optional text string that will be added after the end of the error message

if nargin < 5; optionalSuffix = ''; end
if nargin < 4; optionalPrefix = ''; end
if nargin < 3; winTitle = 'Error'; end

% generate error string
if ~isempty(err.cause)
    cause = err.cause{1}.message;
    errText = sprintf('!!! Error !!!\n\n%s\n%s\n\n%s\n\n%s\n\n%s', optionalPrefix, err.identifier, err.message, cause, optionalSuffix);
else
    errText = sprintf('!!! Error !!!\n\n%s\n%s\n\n%s\n\n%s', optionalPrefix, err.identifier, err.message, optionalSuffix);
end

matlabVersion = ver('matlab');

if isa(guiHandle, 'matlab.ui.Figure') % guide figure
    errordlg(errText, winTitle);
else % appdesigner figure
    if str2num(matlabVersion.Version) < 9.11 % 'Interpreter' is available only from R2021b
        uialert(guiHandle, ...
            errText, ...
            winTitle, 'Icon', 'error');
    else
        uialert(guiHandle, ...
            errText, ...
            winTitle, 'Icon', 'error', 'Interpreter', 'html');
    end
end
end