function Frame = retrievedlg(sisodb)
%RETRIEVEDLG  Opens and manages the Store/Retrieve Compensator dialog.

%   Author(s): P. Gahinet
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.8 $  $Date: 2000/08/02 16:06:43 $

import com.mathworks.mwt.*;
import java.awt.*;

% GUI data structure
LoopData = sisodb.LoopData;
s = struct(...
    'LoopData',LoopData,...
    'Preferences',cstprefs.tbxprefs,...
    'Table',[],...
    'Handles',[],...
    'Listeners',[]);

% Frame
Frame = MWFrame(sprintf('Compensator Designs'));
set(Frame,'HandleVisibility','off');

% Main panel
MainPanel = MWPanel(MWBorderLayout(5,0));
MainPanel.setInsets(Insets(12,5,5,3));
Frame.add(MainPanel,MWBorderLayout.CENTER);
s.Handles = {MainPanel};

% Add list and botton panels
[ListPanel,s] = LocalAddList(Frame,s,sisodb);
[ButtonPanel,s] = LocalAddButton(Frame,s,sisodb);
MainPanel.add(ListPanel,MWBorderLayout.CENTER);
MainPanel.add(ButtonPanel,MWBorderLayout.EAST);

% Layout
Frame.pack;
centerfig(Frame,sisodb.Figure);

% Install listeners
lsnr(1) = handle.listener(LoopData,...
    'ObjectBeingDestroyed',{@LocalClose Frame});
lsnr(2) = handle.listener(LoopData,findprop(LoopData,'SavedDesigns'),...
    'PropertyPostSet',{@LocalRefresh Frame});
s.Listeners = lsnr;

% Set callbacks and store handles 
set(Frame,...
    'WindowClosingCallback',{@LocalHide Frame},...
    'WindowActivatedCallback',{@LocalRefresh Frame},...
    'UserData',s);
LocalRefresh([],[],Frame);  % populate to limit flashing

% Make frame visible
Frame.show;
Frame.toFront;


%--------------------------Callback Functions------------------------

%%%%%%%%%%%%%%%%%
%%% LocalHide %%%
%%%%%%%%%%%%%%%%%
function LocalHide(hSrc,event,f)
% Hide dialog
f.hide;


%%%%%%%%%%%%%%%%%%
%%% LocalClose %%%
%%%%%%%%%%%%%%%%%%
function LocalClose(hSrc,event,f)
% Hide dialog
f.hide;
f.dispose;


%%%%%%%%%%%%%%%%%%%%
%%% LocalRefresh %%%
%%%%%%%%%%%%%%%%%%%%
function LocalRefresh(hSrc,event,Frame)
% Refresh tree view (list of model names)
s = get(Frame,'UserData');
if ~isa(s.LoopData,'sisodata.loopdata')
    % Protect against race condition when SISO Tool is closed
    return
end
SavedDesigns = s.LoopData.SavedDesigns;

% Adjust table size
t = s.Table;
td = t.getData;
nrows = t.getTableSize.height;
ndesigns = length(SavedDesigns);
if ndesigns>nrows
    td.addRows(nrows,nmodels-nrows);
end

% Update table content
for ctrow=1:ndesigns
    Design = SavedDesigns(ctrow);
    td.setData(ctrow-1,0,Design.Name);
    td.setData(ctrow-1,1,sprintf('%d',size(Design.Compensator.Model,'order')));
    td.setData(ctrow-1,2,sprintf('%.3g',abs(get(Design.Compensator.Model,'Ts'))));
end
for ctrow=ndesigns+1:t.getTableSize.height
    for ctcol=1:3,
        td.setData(ctrow-1,ctcol-1,'');
    end
end


%%%%%%%%%%%%%%%%%%%%%
%%% LocalRetrieve %%%
%%%%%%%%%%%%%%%%%%%%%
function LocalRetrieve(hSrc,event,Frame,sisodb);
% Exports selected models
s = get(Frame,'UserData');

% Get selection
t = s.Table;
Selection = 1+double(t.getSelectedRows);
if Selection>length(s.LoopData.SavedDesigns)
    warndlg('You have not specified which compensator to retrieve.','Retrieve Warning','modal');
    return
end

% Retrieve compensator
loadcomp(s.LoopData,Selection);

% Update status bar and history
Status = 'Retrieved compensator.';
sisodb.send('StatusChanged',...
    sisodata.dataevent(sisodb,'StatusChanged',{Status,Status}));


%%%%%%%%%%%%%%%%%%%
%%% LocalDelete %%%
%%%%%%%%%%%%%%%%%%%
function LocalDelete(hSrc,event,Frame,sisodb);
% Exports selected models
s = get(Frame,'UserData');
SavedDesigns = s.LoopData.SavedDesigns;

% Get selection
t = s.Table;
Selection = 1+double(t.getSelectedRows);
if Selection>length(SavedDesigns)
    warndlg('You have not specified which compensator to delete.','Delete Warning','modal');
    return
end

% Start transaction
T = handle.transaction(get(findpackage('sisodata'),'DefaultDatabase'));
set(T,'Name','Delete Compensator','OperationStore','on','InverseOperationStore','on');

% Update design history
DeletedName = SavedDesigns(Selection).Name;
SavedDesigns(Selection,:) = [];
s.LoopData.SavedDesigns = SavedDesigns;

% Commit and register transaction
register(s.LoopData,T);

% Update status bar and history
Status = sprintf('Discarded "%s" from compensator list.',DeletedName);
sisodb.send('StatusChanged',...
    sisodata.dataevent(sisodb,'StatusChanged',{Status,Status}));



%%%%%%%%%%%%%%%%%%%
%%% LocalRename %%%
%%%%%%%%%%%%%%%%%%%
function LocalRename(hSrc,event,f,sisodb)
% Rename compensator
s = get(f,'UserData');
SavedDesigns = s.LoopData.SavedDesigns;

% Get rename info
t = s.Table;
CBdata = get(t,'ValueChangedCallbackData'); % callback data
row = CBdata.row;
col = CBdata.column;

% Check if new name is a valid variable name
NewName = t.getCellData(row,col);
if row<length(SavedDesigns) & isvarname(NewName) & ...
        ~any(strcmp(NewName,{SavedDesigns([1:row,row+2:end]).Name}))
    % Update name
    T = handle.transaction(get(findpackage('sisodata'),'DefaultDatabase'));
    set(T,'Name','Rename Compensator','OperationStore','on','InverseOperationStore','on');
    
    % Update design history
    SavedDesigns(row+1).Name = NewName;
    SavedDesigns(row+1).Compensator.Name = NewName;
    s.LoopData.SavedDesigns = SavedDesigns;
    
    % Commit and register transaction
    register(s.LoopData,T);
    
    % Update status bar and history
    Status = sprintf('Renamed compensator "%s" to "%s."',...
        char(CBdata.previousValue),NewName);
    sisodb.send('StatusChanged',...
        sisodata.dataevent(sisodb,'StatusChanged',{Status,Status}));
else
    % Revert to old name
    t.setCellData(row,col,CBdata.previousValue);
end

    


%--------------------------Rendering Functions------------------------


%%%%%%%%%%%%%%%%%%%%
%%% LocalAddList %%%
%%%%%%%%%%%%%%%%%%%%
function [Panel,s] = LocalAddList(Frame,s,sisodb)
% Adds Export List panel
import com.mathworks.mwt.*;
import java.awt.*;

% Main panel
Panel = MWPanel(MWBorderLayout(0,5));
Panel.setInsets(Insets(5,5,5,5));

% Table view
Table = MWTable(20,3);
Table.setPreferredTableSize(10,4);
Table.getTableStyle.setFont(s.Preferences.JavaFontP);
Table.getColumnOptions.setResizable(1);
Table.getHScrollbarOptions.setMode(-1);
Table.setColumnHeaderData(0,sprintf('Name'));
Table.setColumnHeaderData(1,sprintf('Order'));
Table.setColumnHeaderData(2,sprintf('Sample Time'));
Table.setColumnWidth(0,100);
Table.setColumnWidth(1,80);
Table.setColumnWidth(2,80);
Cstyle = table.Style(table.Style.EDITABLE);
Cstyle.setEditable(1);
Table.setColumnStyle(0,Cstyle);
Cstyle = table.Style(table.Style.BACKGROUND);
Cstyle.setBackground(Color(.94,.94,.94));
Table.setColumnStyle(1,Cstyle);
Cstyle = table.Style(table.Style.BACKGROUND);
Cstyle.setBackground(Color(.94,.94,.94));
Table.setColumnStyle(2,Cstyle);
Table.setAutoExpandColumn(0);
Table.getRowOptions.setHeaderVisible(0);
Topt = Table.getSelectionOptions;
Topt.setMode(1);      % single
Topt.setSelectBy(1);  % by row
set(Table,'ValueChangedCallback',{@LocalRename Frame sisodb})
s.Table = Table;

% Connect components
Panel.add(Table,MWBorderLayout.CENTER);

% Store handle for persistency
s.Handles = [s.Handles ; {Panel}];


%%%%%%%%%%%%%%%%%%%%%%
%%% LocalAddButton %%%
%%%%%%%%%%%%%%%%%%%%%%
function [Panel,s] = LocalAddButton(Frame,s,sisodb)
% Adds control buttons
import com.mathworks.mwt.*;
import java.awt.*;

% Main panel
Panel = MWPanel(MWBorderLayout);
Panel.setInsets(Insets(25,5,25,8));

% Button panel
GL = GridLayout(2,1,0,5);
BP1 = MWPanel(GL);
BP2 = MWPanel(GL);

% Buttons
B1 = MWButton(sprintf('  Retrieve  '));  
B1.setFont(s.Preferences.JavaFontP);
set(B1,'ActionPerformedCallback',{@LocalRetrieve Frame sisodb})
B2 = MWButton(sprintf('Delete'));  
B2.setFont(s.Preferences.JavaFontP);
set(B2,'ActionPerformedCallback',{@LocalDelete Frame sisodb})
B3 = MWButton(sprintf('Help'));       
B3.setFont(s.Preferences.JavaFontP);
set(B3,'ActionPerformedCallback','ctrlguihelp(''sisoretrievedialog'');')
B4 = MWButton(sprintf('Cancel'));  
B4.setFont(s.Preferences.JavaFontP);
set(B4,'ActionPerformedCallback',{@LocalHide Frame})

% Connect components
Panel.add(BP1,MWBorderLayout.NORTH);
Panel.add(BP2,MWBorderLayout.SOUTH);
BP1.add(B1);
BP1.add(B2);
BP2.add(B3);
BP2.add(B4);

% Store handle for persistency
s.Handles = [s.Handles ; {Panel;BP1;BP2;B1;B2;B3;B4}];


