classdef DialogController < handle
    %DIALOGCONTROLLER Controller for DSD error and warning dialog

    %   Copyright 2021 The MathWorks, Inc.

    properties (SetAccess = immutable)
        View
    end

    properties (SetAccess = private)
        Application
        ApplicationListener
        DialogCloseRequestFcns
    end

    properties (Dependent)
        Figure
    end

    methods (Abstract)

        view = createView(this, position,varargin);

    end

    methods % Get / Set

        function fig = get.Figure(this)
            fig = this.View.Figure;
        end

    end

    methods

        function this = DialogController(position,varargin)
            this.View = this.createView(position,varargin{:});
        end

        function attach(this, app)
            if ~isempty(app) && isa(app, 'matlabshared.application.Application')
                this.Application = app;
                this.ApplicationListener = ...
                    addlistener(app, 'ApplicationClosing', @(~,~) this.onCloseRequest());

                % Set app to waiting for duration of dialog lifetime
                w = app.freezeUserInterface();
                this.addCloseRequestFcn(@() delete(w));
            end
        end

        function open(this)
            this.View.show();
        end

        function onCloseRequest(this)
            % Execute all close requests
            cellfun(@(f) f(), this.DialogCloseRequestFcns, 'UniformOutput', false);
        end

        function addCloseRequestFcn(this, fcn)
            this.DialogCloseRequestFcns{end+1} = fcn;
        end
    end
end