% Eventlistener, similar to normal waitbar, but for permutation test
classdef janis_gui_RespondToPermutation< handle

    properties (SetAccess = protected)
        Start;          % Starting time
        h;              % waitbar objet
        Round = 2;      % start with round 2
        Permutations;   % number of permutations
        pval = 1;       % current p-val (which starts with 1)
        lastPerformance;% last predicted perfomance
        appendStr = '';
    end

   methods
       % Constructor
      function obj = janis_gui_RespondToPermutation(permutations, initVal)
         obj.h = waitbar(0, 'Please Wait', 'Name', 'PermutationTest');
         posi = get(obj.h,'Position');
         posi(4) = posi(4) + 100;
         set(obj.h,'Position',posi);
         obj.Start = tic;
         obj.Permutations = permutations;
         obj.lastPerformance = initVal;
      end

      % add eventlistener
      function obj = listenTo(obj,validator_obj)
          addlistener(validator_obj, 'cycle',@(src,evtdata)handleEvnt(obj,src,evtdata));
      end

      % delete object and progressbar
      function delete(obj)
         delete(obj.h);
      end

      % handle the event = update progressbar
      function handleEvnt(obj,src,evtdata)
           timer = toc(obj.Start);
           obj.h = waitbar(obj.Round/obj.Permutations, obj.h, ...
           sprintf('%s\nPermutation Round %d (%d)\n\n p-Val: %1.4f  %% - last performance: %3.1f %%\n\nTime: \nRemaining: %5.1f min. - Elapsed: %5.1f min.\n\n',...
           obj.appendStr, ...
           obj.Round, obj.Permutations, ...
           obj.pval, obj.lastPerformance*100, ...
           ((timer/(obj.Round+src.actualRound/src.getRoundCount)))*(obj.Permutations-(obj.Round+(src.actualRound/src.getRoundCount)))/60, timer/60), obj.appendStr);
           obj.appendStr = [obj.appendStr '.'];
      end

      % update round
      function updateRound(obj, pval, lastPerformance)
           obj.appendStr = '';
           obj.Round = obj.Round + 1;
           obj.pval = pval;
           obj.lastPerformance = lastPerformance;
      end
   end
end