function isWarningShown = checkForSparseWarning(this)
% "checkForSparseWarning" checks if any  system is sparse, and throws a
% warning if needed. It returns a boolean output indicating if a warning
% was thrown.
%
% A warning is thrown if the view contains a time domain plot and the time
% vector or final time is not defined, or if the view contains a frequency
% response plot and the frequency grid is not defined, or if the view
% contains a pole-zero plot.

%   Copyright 2020 The MathWorks, Inc.

isSparseSystem = false;
for k = 1:length(this.Systems)
    % isSparseSystem is true if system is sparse
    if issparse(this.Systems(k).Model)
        isSparseSystem = true;
        break;
    end
end
% Check if warning needs to be shown
isWarningShown = false;
if isSparseSystem && strcmp(this.Figure.Visible,'on')
    needPreferenceDialog = false;
    plotTags = get(this.Views(ishandle(this.Views)),'Tag');
    warnStr = [string(message('Control:viewer:warnSparseSystems'));""];
    % Check for time plots and empty time vector
    if any(contains(plotTags,{'step','impulse','initial'})) && ...
            isempty(this.Preferences.TimeVector)
        warnStr = [warnStr; string(message('Control:viewer:warnSparseTimeVector'))];
        isWarningShown = true;
        needPreferenceDialog = true;
    end
    % Check for frequency plots and empty frequency grid
    if (any(contains(plotTags,{'bode','bodemag','sigma','nyquist','nichols'})) && ...
            (isempty(this.Preferences.FrequencyVector) || iscell(this.Preferences.FrequencyVector)))
        warnStr = [warnStr; string(message('Control:viewer:warnSparseFrequencyGrid'))];
        isWarningShown = true;
        needPreferenceDialog = true;
    end
    % Check for pole-zero plots
    if any(contains(plotTags,{'pzmap','iopzmap'}))
        warnStr = [warnStr; string(message('Control:viewer:warnSparsePoleZeroPlot'))];
        isWarningShown = true;
    end
    % Show warning
    if isWarningShown
        wDialog = warndlg(warnStr,getString(message('Control:viewer:strLTIViewerWarning')),'modal');
%         uiwait(wDialog);
        if needPreferenceDialog
%             openPreferenceDialog(this);
            okButton = findall(wDialog,'Type','uicontrol');
            okButton.Callback = @(es,ed) cbOkButton(this,es);
        end
    end
end
end

function cbOkButton(this,es)
openPreferenceDialog(this);
delete(es.Parent);
end

function openPreferenceDialog(this)
edit(this.Preferences);
selectTab(this.Preferences,'Parameters');
end
