function error = headerForm(hTsgGUI)
%
% Input
% -----
% hTsgGUI ............ Handel to the main user interface
%
% Output
% ------
% error .............. 1: OK ; -1 : an error occured

% $Id$

error = -1;

% Get the data from the application GUI
% -------------------------------------
tsg = getappdata( hTsgGUI, 'tsg_data');

% load platform mat file
% ----------------------
%load platform.mat;

% Define uicontrol start position
% -------------------------------
left   = .01;
bottom = .95;
inc_x  =  0.5;
inc_y  =  0.03;

% set default uicontrol size
% --------------------------
default_height = 0.018;
default_length = .1;

% get actual date
% ---------------
date = datestr(now,30);

% Get global attributes list from class tsg_nc with file 'tsg_ncattr.csv'
% -----------------------------------------------------------------------
nca      = tsg_nc('tsg_ncattr.csv');
nca_keys = keys(nca);

% Load platform_info object from tsg_platform_info.mat file
% see: Use the form of load that returns a MATLAB structure.
% ---------------------------------------------------------
s = load( 'tsg_platform_info.mat' );
platform_info = s.platform_info;

% header Uicontrols in a new figure
% ---------------------------------
hHeaderFig = figure(...
   'BackingStore','off',...
  'Name', 'TSG GLOBAL ATTRIBUTES', ...
  'NumberTitle', 'off', ...
  'Resize', 'on', ...
  'Menubar','none', ...
  'Toolbar', 'none', ...
  'Tag', 'GLOBAL_ATTRIBUTES', ...
  'Visible','on',...
  'Units', 'normalized',...
  'Position',get(hTsgGUI,'Position'), ...
  'Color', get( 0, 'DefaultUIControlBackgroundColor' ));

% bg = [0.92549 0.913725 0.847059] = get( 0, 'DefaultUIControlBackgroundColor' );

% Iterate from each element from object nca
% -------------------------------------
for i=1:numel(nca_keys)
  
  % get key, use {} for cell
  % ------------------------
  key = nca_keys{i};
  
  % get all structure for the key
  % -----------------------------
  s = get(nca, key);
  
  % set tsg.DATE_UPDATE
  % -------------------
  if strcmp(key, 'DATE_UPDATE')
    tsg.(key) = [date(1:8) date(10:15)];
  end
  
  % check for empty field and replace them by default value
  % -------------------------------------------------------
  if isempty(s.length), s.length = default_length; end;
  if isempty(s.height), s.height = default_height; end;
      
  % display dynamically uicontrol text
  % use of char function to prevent error when field is empty [] => ''
  % ------------------------------------------------------------------
  uicontrol(...
    'Parent', hHeaderFig, ...
    'Units', 'normalized', ...
    'Style', 'Text', ...
    'Fontsize', tsg.fontSize-1, ...
    'HorizontalAlignment', 'left', ...
    'Position',[left, bottom, .13, .0135], ...
    'TooltipString', char(s.comment), ...
    'String', char(s.name) );
  
  % display dynamically uicontrol 
  % -----------------------------
  ui = uicontrol(...
    'Parent', hHeaderFig, ...
    'Units', 'normalized', ...
    'BackgroundColor', 'w', ...
    'Style', char(s.uicontrolType), ...
    'Fontsize', tsg.fontSize-2, ...
    'HorizontalAlignment', char(s.horizontalAlignment), ...
    'Position',[left+.11, bottom, s.length, s.height], ...
    'String', char(s.string), ...
    'Value', s.value, ...
    'Tag', key);
  
  % display conventions field if exist 
  % ----------------------------------
  uicontrol(...
    'Parent', hHeaderFig, ...
    'Units', 'normalized', ...
    'Style', 'text', ...
    'Fontsize', tsg.fontSize-2, ...
    'HorizontalAlignment', 'left', ...
    'Position',[left+.22, bottom, .1, s.height], ...
    'String', char(s.conventions) );

  % set dynamically uicontrol from tsg struct
  % -----------------------------------------
  switch s.uicontrolType
    case 'popupmenu'
      str = cellstr(get(ui,'String'));
      ind = strfind(str,tsg.(key));
      for k=1:numel(ind)
        if ~isempty(ind{k})
          set(ui, 'value', k);
        end
      end
    case 'edit'
      set(ui, 'string', tsg.(key));
    case 'checkbox'
      % not yet implemented !!!
  end
  
  % Check vertical position of last uicontrol and creation new colomn
  % -----------------------------------------------------------------
  bottom = bottom - inc_y;
  if bottom < .15
    bottom = 0.95;
    left = left + inc_x;
  end  
end

% set a callback to PLATFORM_NAME uicontrol
% -----------------------------------------
set(findobj('Tag','PLATFORM_NAME'),'Callback', @updateForm);

% CONTINUE PUSH BUTTON
% --------------------
% The Continue (valid)  button
uicontrol( ...
  'Parent', hHeaderFig, ...
  'Style','pushbutton',...
  'Fontsize', tsg.fontSize,...
  'Units', 'normalized', ...
  'Position',[.05, .1, .05, .02],...
  'String','Continue',...
  'Interruptible','off',...
  'BusyAction','cancel',...
  'Tag','PUSH_BUTTON',...
  'Callback', @continueCallback);

% CANCEL PUSH BUTTON
% ------------------
% The cancel  button
uicontrol( ...
  'Parent', hHeaderFig, ...
  'Style','pushbutton',...
  'Fontsize', tsg.fontSize,...
  'Units', 'normalized', ...
  'Position',[.15, .1, .05, .02],...
  'String','Cancel',...
  'Interruptible','off',...
  'BusyAction','cancel',...
  'Tag','PUSH_BUTTON',...
  'Callback', @cancelCallback);

% Build structure container for graphic handles with tag property defined.
% ------------------------------------------------------------------------
data = guihandles(hHeaderFig);

% record data struct in application data object 
% ---------------------------------------------
% guidata(hHeaderFig, data);

% stop execution until push-button Continue was press
% ---------------------------------------------------
uiwait(hHeaderFig);

%% Nested callback

  % -----------------------------------------------------------------------
  % Continue action, get uicontrol fields and populate tsg structure
  % -----------------------------------------------------------------------
  function continueCallback(obj, event)
    
    % Iterate from each element from object nca
    % -------------------------------------
    for ii=1:numel(nca_keys)

      % get key, use {} for cell
      % ------------------------
      key = nca_keys{ii};
      
      % get all structure for the key
      % -----------------------------
      s = get(nca, key);
      
      % get the corresponding string from uicontrol using guihandles
      % data (dynamic)
      % ------------------------------------------------------------
      tsg.(key) = get(data.(key), 'string');
      
      % if uicontrol is a popupmenu, string is cell array with all choices
      % ------------------------------------------------------------------
      if strcmp(s.uicontrolType,'popupmenu')
        
        % get the corresponding string from cell array  using selected value
        % ------------------------------------------------------------------
        tsg.(key) = deblank(tsg.(key)(get(data.(key), 'value'),:));
        
      end
      
      % set and update pi (platform_info) structure from tsg only with
      % corresponding field before save
      % --------------------------------------------------------------
      if isfield(platform_info, key)
        pi.(key) = tsg.(key);
      end
       

    end
    
    % Save tsg structure 
    % ------------------
    setappdata( hTsgGUI, 'tsg_data', tsg);
 
    % get the uicontrol PLATFORM_NAME value as key, use tag to retrieve
    % -----------------------------------------------------------------
    key = get(findobj('Tag','PLATFORM_NAME'),'string');
    
    % Update plateform_info object with this key and platform_name
    % updated structure
    % --------------------------------------------------------------
    platform_info = set(platform_info, key, pi);
    
    % save object in mat file, use what to find tsg_nc path
    % -----------------------------------------------------
    w = what( 'tsg_nc');
    save([w.path filesep 'tsg_platform_info.mat'], 'platform_info');
    
    % close windows (replace call to uiresume(hHeaderFig))
    % ----------------------------------------------------
    close(hHeaderFig);
    
    % flushes the event queue and updates the figure window
    % -----------------------------------------------------
    drawnow;
    
    % return no error code (true)
    % ---------------------------
    error = 1;
    
  end

  % -----------------------------------------------------------------------
  % Cancel button, no action
  % -----------------------------------------------------------------------
  function cancelCallback(obj, event)
    
    % close windows
    % -------------
    close(hHeaderFig);
    
    % flushes the event queue and updates the figure window
    % -----------------------------------------------------
    drawnow;
    
    % return error code (no change)
    % -----------------------------
    error = -1;
    
  end

  % -----------------------------------------------------------------------
  % Callback when uicontrol PLATFORM_NAME is modified
  % -----------------------------------------------------------------------
  function updateForm(obj, event)
    
    % get the new value, use tag to retrieve
    % --------------------------------------
    value = get(findobj('Tag','PLATFORM_NAME'),'string');
    
    % get platform_name structure from platform_info object (mat file)
    % ----------------------------------------------------------------
    platform_name = get(platform_info, value);
    
    % if this platform exist, structure not empty
    % -------------------------------------------
    if ~isempty(platform_name)
      
      % get members list of structure platform_name
      % -------------------------------------------
      nb = fieldnames(platform_name);
      
      % iterate on all members
      % ----------------------
      for ii=1:numel(nb)
        
        % key member name and use it as a key for tsg structure
        % -----------------------------------------------------
        key = nb{ii};
        tsg.(key) = platform_name.(key);
        
        % update headerform fields with values from mat file
        % --------------------------------------------------
        set(findobj('Tag', key),'string',tsg.(key));
        
        % with different color
        % --------------------
        set(findobj('Tag', key),'foregroundColor', 'r');
        
      end
      
    % if user enter a new PLATFORM_NAME, open a question dialog box for
    % confirmation
    % ----------------------------------------------------------------- 
    else
      selection = ...
        questdlg('This PLATFORM NAME is new.  Do you want to use and save it ?',...
        'Create new PLATFORM NAME ?',...
        'Yes', 'No', 'No');
      
      % if yes, continue, create and save new PLATFORM_NAME in mat file
      % ---------------------------------------------------------------
      if strcmp(selection, 'Yes')
        return;
        
      % if not, reset field
      % -------------------
      else
        set(findobj('Tag','PLATFORM_NAME'),'string', '');
      end
    end
    
  end

end

