function session_menu(par, user)

% session_menu - create menu for user sessions
% --------------------------------------------
%
% session_menu(par, user)
%
% Input:
% ------
%  par - menu parent
%  user - user (def: active user)

% NOTE: consider using a single 'File' menu on the XBAT palette

%----------------------
% HANDLE INPUT
%----------------------

if nargin < 2
	user = get_active_user; 
end

%----------------------
% SETUP
%----------------------

%--
% clear former menu if needed
%--

top = findobj(par, 'type', 'uimenu', 'tag', 'TOP_SESSION_MENU');

if ~isempty(top)
	delete(allchild(top));
end

%----------------------
% CREATE MENUS
%----------------------

%--
% create top menu if needed
%--

if isempty(top)
	top = uimenu(par, 'label', 'Session', 'tag', 'TOP_SESSION_MENU');
end 

%--
% create command menus
%--

uimenu(top, ...
	'label', 'Save ...', ...
	'callback', {@save_session_callback, par, user} ...
);

uimenu(top, ...
	'label', 'Load ...', ...
	'callback', {@load_session_callback, user} ...
);

%--
% create session menus
%--

names = get_sessions('', user); 

if isempty(names)
	
	uimenu(top, ...
		'label', '(No Sessions Found)', ... 
		'enable', 'off', ...
		'separator', 'on' ...
	);

else

	named = [];

	for k = 1:length(names)
		named(end + 1) = uimenu(top, ...
			'label', names{k}, ...
			'callback', {@open_session_callback, user} ...
		);
	end

	set(named(1), 'separator', 'on');
	
	uimenu(top, ...
		'label', 'Show Files ...', ...
		'separator', 'on', ...
		'callback', {@show_files_callback, user} ...
	);

end


%--------------------------------------
% SAVE_SESSION_CALLBACK
%--------------------------------------

function save_session_callback(obj, eventdata, par, user)

%--
% present dialog to save session
%--

info = save_session_dialog(user);

% NOTE: return if no session was saved

if isempty(info)
	return;
end 

%--
% rebuild session menu
%--

session_menu(par, user);


%--------------------------------------
% LOAD_SESSION_CALLBACK
%--------------------------------------

function load_session_callback(obj, eventdata, user)

load_session_dialog(user);


%--------------------------------------
% OPEN_SESSION_CALLBACK
%--------------------------------------

function open_session_callback(obj, eventdata, user)

open_session(get(obj, 'label'), user);


%--------------------------------------
% SHOW_FILES_CALLBACK
%--------------------------------------

function show_files_callback(obj, eventdata, user)

show_file(sessions_root(user));




