#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import GLib
# from gi.repository import StatusIcon
import time
import os
from subprocess import Popen
from subprocess import check_output

alarm_time = (60 * 25)

def message(data=None):
  msg = Gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, data)
  msg.run()
  msg.destroy()

def quit_app(data=None):
  Gtk.main_quit()

def make_menu(event_button, event_time, data=None):
  menu = Gtk.Menu()
  quit_item = Gtk.MenuItem("Quit")
  menu.append(quit_item)
  quit_item.connect_object("activate", quit_app, "Quit")
  quit_item.show()
  menu.popup(None, None, None, None, event_button, event_time)

def on_right_click(data, event_button, event_time):
  make_menu(event_button, event_time)

def on_left_click(event):
  timer.toggle_timer()

class CrudeIPC(object):
  def __init__(self):
    self.output_file_path = os.getenv('XDG_RUNTIME_DIR') + "/tomtim"
    print(self.output_file_path);

  def write_out(self, string):
    self.in_memory_file = open(self.output_file_path, 'w')
    self.in_memory_file.write(str(alarm_time) + "\n")
    self.in_memory_file.write(string + "\n")
    self.in_memory_file.close()

class Timer(object):
  def __init__(self):
    GLib.timeout_add(1000, self.tick)
    self.start_time = time.time()
    self.timer_state = "stopped"
    self.ipc = CrudeIPC()

  def tick(self):
    if self.timer_state == "running":
      current_time = time.time() - self.start_time
      self.ipc.write_out(str(int(alarm_time - current_time)))
      if current_time > alarm_time:
        self.ring_alarm()
    else:
      self.ipc.write_out(str(alarm_time))

    return True

  def toggle_timer(self):
    if self.timer_state == "stopped":
      self.start_timer()
    else:
      self.stop_timer()

  def start_timer(self):
    self.start_time = time.time()
    self.timer_state = "running"
    icon.set_from_icon_name(Gtk.STOCK_STOP)

  def stop_timer(self):
    self.timer_state = "stopped"
    icon.set_from_icon_name(Gtk.STOCK_YES)

  def ring_alarm(self):
    p = Popen(["aplay", self.__alarm_sound_path()])
    message("Times up!")
    self.stop_timer()

  def __alarm_sound_path(self):
    base_dir = os.path.dirname(os.path.realpath(__file__))
    return base_dir + "/alarm.wav"

if __name__ == '__main__':
  icon = Gtk.StatusIcon()
  icon.set_from_icon_name(Gtk.STOCK_YES)
  icon.connect('popup-menu', on_right_click)
  icon.connect('activate', on_left_click)
  timer = Timer()
  Gtk.main()
