
%

%   Copyright 2014 The MathWorks, Inc.

classdef BlockSelector < handle
    % A Block Selector listen to the Editor's SelectionChangeEvent
    properties
        selectionChangeHandler  % Function handle
        model
        active  = false % Bool
        blockSelection
        signalSelection
        dlg = [];
        
        refMdlSelectionChangeHandler % handler for referenced models
    end
    
    
    methods
        function listenTo(this, mdlH, obj)
            this.model = get(mdlH, 'Object');
            this.selectionChangeHandler = Simulink.listener(this.model, ...
                'SelectionChangeEvent', @(h,ev)updateSelection(this));

            refMdlHs = loadNormalMdlref(mdlH);
            handlers = cell(numel(refMdlHs),1);
            for i=1:length(refMdlHs)
                handlers{i} = Simulink.listener(refMdlHs(i), ...
                    'SelectionChangeEvent', @(h,ev)updateSelection(this));
            end
            this.refMdlSelectionChangeHandler = handlers;
            
            this.active = true;
            this.dlg = obj;
            
            updateSelection(this);
            
        end
        
        function stop(this)
            this.model = [];
            this.selectionChangeHandler = [];
            this.refMdlSelectionChangeHandler = [];
            this.active = false;
            this.blockSelection = [];
            this.signalSelection = [];
           
        end
    end
    
end

function updateSelection(this)
[this.blockSelection, this.signalSelection] = getSelectionHandles();
obj = this.dlg.getWidgetSource('EditorSelectionText');
obj.noSelection = isempty(this.blockSelection) && ...
    isempty(this.signalSelection);
this.dlg.refresh;

end


function refMdlHs = loadNormalMdlref(mdlH)
    import Simulink.ModelReference.internal.*;
    
    allMdlNames = find_normal_mdlrefs(mdlH);
    refMdlNames = setdiff(allMdlNames, get(mdlH, 'Name'));
    refMdlHs = [];
    for i = 1:length(refMdlNames)
        load_system(refMdlNames{i}); 
        refMdlHs = [refMdlHs; get_param(refMdlNames{i}, 'Handle')];
    end
end
