% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <https://www.gnu.org/licenses/>

% Author: Ilya Belevich, University of Helsinki (ilya.belevich @ helsinki.fi)
% part of Microscopy Image Browser, http:\\mib.helsinki.fi 
% Date: 25.04.2023

function showErrorDialog(parent, err, winTitle, optionalPrefix, optionalSuffix)
% function showErrorDialog(parent, err, winTitle, optionalPrefix, optionalSuffix)
% show error that is generated in try/catch blocks
%
% Parameters:
% parent: handle to the parent window
% 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

% Updates
% 

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

% copy error text to clipboard
clipboard('copy', errText);

if isa(parent, 'matlab.ui.Figure')
    % guide figure
    warndlg(errText, ...
        winTitle, ...
        'non-modal');
else
    % appdesigner window
    v = ver('matlab');
    if obj.matlabVersion < str2double(v.Version) % 'Interpreter' is available only from R2021b
        uialert(parent, ...
            errText, ...
            winTitle, 'Icon', 'error');
    else
        uialert(parent, ...
            errText, ...
            winTitle, 'Icon', 'error', 'Interpreter', 'html');
    end
end
end