#!/bin/ruby
require "Win32API"
require "win32/guitest"
include Win32::GuiTest

CHECK_STRING_LIST = ["Wikipedia", "YouTube", "Yahoo", "ITmedia", "blog", "news"];
TIME_LIMIT = 10;
CHECK_INTERVAL1 = 300;
CHECK_INTERVAL2 = 3;

msgbox = Win32API.new('user32', 'MessageBox', %w(p p p i), 'i');
n = CHECK_STRING_LIST.length;
isActive = Array.new(n, false);
activeSince = Array.new(n, 0);
texts = Array.new(n);
p CHECK_STRING_LIST

while (true) 
  activeExists = false;
  for i in 0...n
    isActive[i] = false;
  end
  enumWindows {|win|
    wintext = win.getWindowText;
    for i in 0...n
      if (/#{CHECK_STRING_LIST[i]}/i =~ wintext)
        isActive[i] = true;
        activeExists = true;
        texts[i] = wintext;
      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] + "\".";
          msgbox.call(0, msg, "Go back to your work", 0x00050000);
        end
      end
    else
      activeSince[i] = 0;
    end
  end
  if (activeExists)
    sleep(CHECK_INTERVAL2);
  else
    sleep(CHECK_INTERVAL1);
  end
end
