#!/usr/bin/env python3
"""
Take a Break 0.5
Copyright (C) 2015  Jacob Vlijm
contact: vlijm@planet.nl
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or any later version. This
program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details. You
should have received a copy of the GNU General Public License along with this
program.  If not, see <http://www.gnu.org/licenses/>.
"""

from gi.repository import Gio
import subprocess
import sys
import time

def parse_args(arg):
    return arg.split(":")[1]

# set default settings
args = [
    "awaketime:50",
    "sleeptime:10",
    "mode:dim",
    "notify_msg:True",
    "notify_time:15",
    "from_unidle:False"
    ]
# replace defaults by possibly set values
edit_args = sys.argv[1:]

for i, item in enumerate(args):
    for edited_arg in edit_args:
        args[i] = edited_arg if item.startswith(
            edited_arg.split(":")[0]
            ) else args[i]
    args[i] = parse_args(args[i])

awaketime = int(args[0])*60
sleeptime = int(args[1])*60
mode = args[2]
notify_msg = eval(args[3])
notify_time = int(args[4])
from_unidle = eval(args[5])

message = "Break in "+str(notify_time)+" seconds"

def get_idle():
    return int(subprocess.check_output(["xprintidle"]).decode("utf-8"))

def idle_sleep():
    curr_idle1 = get_idle()
    while True:
        time.sleep(3)
        curr_idle2 = get_idle()
        if curr_idle2 <= curr_idle1:
            break
        else:
            curr_idle1 = curr_idle2

def screensaver_command(method, value):
    names = ["org.freedesktop.ScreenSaver",
             "org.gnome.ScreenSaver",
             "org.mate.ScreenSaver"]
    paths = ["/org/freedesktop/ScreenSaver",
             "/org/gnome/ScreenSaver",
             "/org/mate/ScreenSaver"]

    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    for i in range(len(names)):
        proxy = Gio.DBusProxy.new_sync(bus, 0, None, names[i], paths[i], names[i], None)
        proxy.call(method, value, 0, 0, None, None)
            
def take_a_break():
    get = subprocess.check_output(["xrandr"]).decode("utf-8").split()
    screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"]
    if mode == "message":
        command = "/usr/share/takeabreak/takeabreak/message_window"
        subprocess.Popen([command, str(sleeptime)])
    else:
        for scr in screens:
            if mode =="rotate":
                subprocess.call([
                    "xrandr", "--output", scr, "--rotate", "inverted"
                    ])
            elif mode == "dim":
                subprocess.call([
                    "xrandr", "--output", scr, "--brightness", "0"
                    ])
            elif mode == "lock":
                screensaver_command("Lock", None)
            elif mode == "screensaver":
                screensaver_command("SetActive", GLib.Variant("(b)", (True,)))
                screensaver_command("Lock", None)
    time.sleep(sleeptime)
    for scr in screens:
        screensaver_command("SetActive", GLib.Variant("(b)", (False,)))
        time.sleep(2)
        if mode == "rotate":
            subprocess.call([
                "xrandr", "--output", scr, "--rotate", "normal"
                ])
            time.sleep(0.2)
        elif mode == "dim":
            subprocess.call([
                "xrandr", "--output", scr, "--brightness", "1"
                ])
            time.sleep(0.2)            
    if from_unidle == True:
        idle_sleep()

if from_unidle == True:
    idle_sleep()

while True:
    time.sleep(awaketime-notify_time)
    if notify_msg == True:
        subprocess.Popen(["notify-send", message])
    time.sleep(notify_time)
    take_a_break()




    


