% BUILDHLQPANEL build the High Level Queries panel.
%
% N Tateo 16-04-09
%
% $Id: buildHLQPanel.m,v 1.6 2011/04/08 08:56:25 hewitson Exp $
%
function buildHLQPanel(mainfig)
  
  import utils.const.*
  utils.helper.msg(msg.PROC1, 'building High Level Queries Panel');
  
  htab = mainfig.panels(5);
  
  Gproperties = mainfig.Gproperties;
  pmarg = 0.025;
    
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % List of HLQs:
  
      hlq_name = 'ao.name = ''name'' AND tsdata.t0 > x';
      hlq_desc = 'Select AOs with tsdata of given channel name and initial time successive to a given t0.';
      hlq_str  = ['select objmeta.obj_id from objmeta,ao,tsdata '...
                 'where objmeta.obj_id = ao.obj_id '...
                 'and ao.data_id = tsdata.id '...
                 'and objmeta.name=''var_1'' '...
                 'and tsdata.t0>=''var_2'''];
     % Each HLQ has its proper list of parameters to set. Each parameter is
     % defined inside a plist:
     %  - name: the name of the parameters to set.
     %  - type: edit, list, popup, time.
     %  - values: if list/popup, the possible values to choose among.
     %  - default: the default value associated to the parameter.
     hlq_vars.v1 = plist( ...
         'name',      'Name:', ...
         'type',      'string', ...
         'values',    [], ...
         'default',   'x1');
     hlq_vars.v2 = plist( ...
         'name',      'Initial time:', ...
         'type',      'time', ...
         'values',    [], ...
         'default',   '1970-01-01 00:00:00.000');
  hlq1 = {hlq_name , hlq_desc , hlq_str , hlq_vars};
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
     hlq_name = 'ao.name = ''name'' AND x < tsdata.t0 < y';
     hlq_desc = 'Select AOs with tsdata of given channel name and initial time comprised in a given interval';
     hlq_str  = ['select objmeta.obj_id from objmeta,ao,tsdata ' ...
             'where objmeta.obj_id=ao.obj_id ' ...
             'and ao.data_id=tsdata.id ' ...
             'and objmeta.name = ''var_1'' ' ...
             'and tsdata.t0 >= ''var_2'' ' ...
             'and tsdata.t0+INTERVAL tsdata.nsecs SECOND  <= ''var_3'' '];
     
     hlq_vars.v1 = plist( ...
         'name',      'Name:', ...
         'type',      'string', ...
         'values',    [], ...
         'default',   'x1');
     hlq_vars.v2 = plist( ...
         'name',      'Initial time:', ...
         'type',      'time', ...
         'values',    [], ...
         'default',   '1970-01-01 00:00:00.000');
     hlq_vars.v3 = plist( ...
         'name',      'Final time:', ...
         'type',      'time', ...
         'values',    [], ...
         'default',   '1970-01-02 00:00:00.000');
  hlq2 = {hlq_name , hlq_desc , hlq_str , hlq_vars};

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%      hlq_name = 'Query name 3';
%      hlq_desc = 'Query description';
%      hlq_str  = 'query_string';
%      hlq_vars.v1 = plist( ...
%          'name',      '', ...
%          'type',      '', ...
%          'values',    [], ...
%          'default',   []);
%      hlq_vars.v2 = plist( ...
%          'name',      '', ...
%          'type',      '', ...
%          'values',    [], ...
%          'default',   []);
%   hlq3 = {hlq_name , hlq_desc , hlq_str , hlq_vars};
  
  
  HLQ = [ hlq1 ; hlq2 ];
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  
  CommonHeight = 0.06;

% header
  bw = 0.4;
  bl = pmarg;
  bh = CommonHeight;
  bb = 1-2*pmarg-bh;
  hlqText = uicontrol(htab, 'Style','text',...
    'String', 'High Level Queries:',...
    'BackgroundColor', 'w', ...
    'Units', 'normalized', ...
    'Userdata',1,...
    'Fontsize', Gproperties.fontsize+2, ...
    'Position',[bl bb bw bh]);
   
% list box
  bh = 0.65;
  bb = bb - bh - .03;
  hlqListbox = uicontrol(htab,'Style','list',...
    'String',HLQ(:,1),...
    'Min',1,...
    'Max',1,...
    'BackgroundColor', 'w',...
    'Fontsize', Gproperties.fontsize,...
    'Units', 'normalized', ...
    'Position', [bl bb bw bh],...
    'TooltipString', 'These are the supported High Level Queries',...
    'UserData', HLQ, ...
    'Tag', 'RepoguiHLQList' , ...
    'Callback' , @hlqListboxCbk );

% description field
  bh = 0.2;
  bb = bb - bh - .03;
  bw = .3;
  hlqDescbox = uicontrol(htab,'Style','text',...
    'String',HLQ{1,2},...
    'BackgroundColor', 'w',...
    'Fontsize', Gproperties.fontsize,...
    'Units', 'normalized', ...
    'Position', [bl bb bw bh],...
    'Tag', 'RepoguiHLQDesc');

% set button
  bh = 0.1;
  bw = 0.1;
  bl = .4 + pmarg - bw;
  pbh = uicontrol(htab,'Style','pushbutton',...
    'String','Set',...
    'Callback', {'repogui.cb_submit', mainfig}, ...
    'Units', 'normalized', ...
    'Fontsize', Gproperties.fontsize, ...
    'Position',[bl bb+.1 bw bh], ...
    'Tag','hlqSetButton', ...
    'Callback' , @hlqSetButtonCbk );

% query button
  uicontrol(htab, ...
      'Style','pushbutton', ...
      'String','Execute query', ...
      'Units', 'normalized', ...
      'Position',[.7 0 .29 .06], ...
      'Tag', 'executeHLQbutton', ...
      'Callback', @hlqExecQuery, ...
      'Userdata', mainfig, ...
      'enable', 'off');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Dynamical part of the panel

  bl = .45;
  bb = .08;
  bw = .54;
  bh = .88;
  dynpanel = uipanel(htab, ...
      'BackGroundColor', 'w', ...
      'Title' , 'Query settings:', ...
      'Position', [bl bb bw bh], ...
      'Tag', 'dynamicPanel', ...
      'Visible', 'on');
  

  

  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

function hlqListboxCbk(hObject,varargin)
   % Callback associated to the HLQ listbox

   currVal = get(hObject,'Value');
   hlq = get(hObject,'UserData');
   currHLQ = hlq(currVal,:);
   set(findobj(gcf,'Tag','RepoguiHLQDesc'),'String',currHLQ{2})

end

function hlqSetButtonCbk(hObject,varargin)
   % Callback associated to the set button

   currVal = get(findobj(gcf,'Tag','RepoguiHLQList'),'Value');
   hlq = get(findobj(gcf,'Tag','RepoguiHLQList'),'UserData');
   hlq = hlq(currVal,:);
   hlq_vars = hlq{4};
   dynPanel = findobj(gcf,'Tag','dynamicPanel');
   set(dynPanel,'Visible','on');
   set(findobj(gcf,'Tag','executeHLQbutton'),'enable','on')
   delete(findobj(gcf,'Parent',dynPanel))
   drawDynamicPanel(dynPanel, hlq_vars,get(hObject,'FontSize'))

end

function drawDynamicPanel(dynPanel, hlq_vars, fontsize)
   % To draw the dynamic panel, showing all query settings.

   bl = .05;
   bb = .95;
   bh = .1;
      
   var_numb = numel(fieldnames(hlq_vars));
   for ii = 1:var_numb
       curr_var = ['v' num2str(ii)];
       curr_var = hlq_vars.(curr_var);
       % this is the plist
       var_name = find(curr_var,'name');
       var_type = find(curr_var,'type');
       var_val  = find(curr_var,'default');
       
       bb = bb - .12;
       bw = .4;
       
       switch var_type
           case 'string'
               uicontrol(dynPanel, ...
                   'Style','text', ...
                   'String', var_name, ...
                   'HorizontalAlignment', 'right', ...
                   'BackgroundColor', 'w', ...
                   'ForegroundColor', 'k', ...
                   'Fontsize', fontsize+1, ...
                   'Units', 'normalized', ...
                   'Position',[bl bb bw bh]);
               uicontrol(dynPanel, ...
                   'Style','edit', ...
                   'String', var_val, ...
                   'HorizontalAlignment', 'center', ...
                   'BackgroundColor', 'w', ...
                   'ForegroundColor', 'k', ...
                   'Fontsize', fontsize+1, ...
                   'Units', 'normalized', ...
                   'Position',[bl+bw+.02 , bb+.038 , bw+.08 , .08],...
                   'Tag',['var_' num2str(ii)]);
               
           case 'time'
               bw = .3;
               uicontrol(dynPanel, ...
                   'Style','text', ...
                   'String', var_name, ...
                   'HorizontalAlignment', 'right', ...
                   'BackgroundColor', 'w', ...
                   'ForegroundColor', 'k', ...
                   'Fontsize', fontsize+1, ...
                   'Units', 'normalized', ...
                   'Position',[bl-.03 bb bw-.05 bh]);
               uicontrol(dynPanel, ...
                   'Style','edit', ...
                   'String', var_val, ...
                   'TooltipString', 'epoch in milliseconds [0] or time string [1970-01-01 00:00:00.000]', ...
                   'HorizontalAlignment', 'center', ...
                   'BackgroundColor', 'w', ...
                   'ForegroundColor', 'k', ...
                   'Fontsize', fontsize+1, ...
                   'Units', 'normalized', ...
                   'Position',[bl+bw-.06 , bb+.038 , bw+.18 , .08],...
                   'Tag',['var_' num2str(ii)], ...
                   'Callback', @checkTimeInput );
                   prefs = getappdata(0, 'LTPDApreferences');
                   timezoneList = utils.timetools.getTimezone;
                   currTimeZone = find(ismember(timezoneList,prefs.time.timezone));
                   uicontrol(dynPanel, ...
                       'Style','popupmenu', ...
                       'String', timezoneList, ...
                       'Value', currTimeZone, ...
                       'TooltipString', 'Timezone', ...
                       'HorizontalAlignment', 'center', ...
                       'BackgroundColor', 'w', ...
                       'ForegroundColor', 'k', ...
                       'Fontsize', fontsize+1, ...
                       'Units', 'normalized', ...
                       'Position',[bl+bw+.435 , bb+.038 , .2 , .08],...
                       'Tag',['timezone_' num2str(ii)], ...
                       'Callback' , 'set(findobj(gcf,''TooltipString'',''Timezone''),''Value'',get(gco,''Value''))' );
               
               
       end
       
   end

end

function checkTimeInput(hObject, varargin)

   input = get(hObject,'String');
   if ~isnan(str2double(input))
       date_str = datestr(str2double(input),'yyyy-mm-dd HH:MM:SS.FFF');
       set(hObject,'String',date_str);
   end
       
end

function hlqExecQuery(hObject,varargin)
   % Callback associated to the set button

   mainfig = get(hObject,'Userdata');
   HLQlist = findobj(gcf,'Tag','RepoguiHLQList');
   HLQ = get(HLQlist,'Userdata');
   currHLQ = get(HLQlist,'Value');
   currHLQ = HLQ(currHLQ,:);
   hlq_str  = currHLQ{3};
   hlq_vars = currHLQ{4};
   var_numb = numel(fieldnames(hlq_vars));
   
   for ii=1:var_numb
       var_str = findobj(gcf,'Tag',['var_' num2str(ii)]);
       var_str = get(var_str,'String');
       
       var_type = find(hlq_vars.(['v' num2str(ii)]), 'type');
%        switch var_type
%            case 'time'
%                % Convert the string in UTC timezone
%                timezone = get(findobj(gcf,'Tag',['timezone_' num2str(currVal)]),'Value');
%                timezoneList = utils.timetools.getTimezone;
%                timezone = timezoneList(timezone);
%                if ~strcmp(timezone,'UTC')
%                    var_str = char(setTimezone( time(plist('time_str',time_str,'timezone',timezone) ,'UTC'));
%                end
%        end
       
       hlq_str = strrep(hlq_str, ['var_' num2str(ii)], var_str);
   end
   
   repogui.cb_executeQuery(hlq_str,mainfig)
   
end
