#!/usr/local/bin/ruby
require "tk"

CHECK_STRING_LIST = ["Wikipedia", "YouTube", "Yahoo", "ITmedia", "blog", "news", "アンサイクロペディア", "ウィキペディア", "NBonline"];
TIME_LIMIT = 5;
CHECK_INTERVAL1 = 60; # originally 300;
CHECK_INTERVAL2 = 5;

n = CHECK_STRING_LIST.length;
isActive = Array.new(n, false);
activeSince = Array.new(n, 0);
texts = Array.new(n);
print "SaboriChecker ver.0.11 developed by Tetsuro Kitahara\n";
p CHECK_STRING_LIST

while (true) 
  activeExists = false;
  for i in 0...n
    isActive[i] = false;
  end
  `xwininfo -root -tree`.each { |line|
    for i in 0...n
      if (/#{CHECK_STRING_LIST[i]}/i =~ line)
        isActive[i] = true;
        activeExists = true;
        texts[i] = line;
      end
    end
  }
  for i in 0...n
    if (isActive[i])
      if (activeSince[i] == 0)
        activeSince[i] = Time.now.tv_sec;
      else
        length = Time.now.tv_sec - activeSince[i];
        print "A window including the keyword \"#{CHECK_STRING_LIST[i]}\" " + \
              "has been active for #{length / 60} minutes.\n";
        if (length >= 60 * TIME_LIMIT)
          msg = (length / 60).to_s + \
                " minutes have passed since you had opened \"" + \
                texts[i] + "\".";
          `gnome-screensaver ; gnome-screensaver-command --lock`;
#          Tk.messageBox('message'=>msg);
##          TkDialog.new("message"=>msg, "buttons"=>"Ok", "default"=>0, 
##                       "bitmap"=>"warning");
        end
      end
    else
      activeSince[i] = 0;
    end
  end
  if (activeExists)
    sleep(CHECK_INTERVAL2);
  else
    sleep(CHECK_INTERVAL1);
  end
end
