#! /usr/bin/python3
import ast
import subprocess
import time
import bhctools as bhc

"""
Hot Corners
Author: Jacob Vlijm
Copyright=Copyright © 2017 Ubuntu Budgie Developers
Website=https://ubuntubudgie.org
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/>.
"""


def watch():
    t = 0.5
    n = 0
    res = None
    corner1 = None

    while True:
        time.sleep(t)
        # check resolution once per 5 seconds
        if n == 0:
            res2 = bhc.getres()
            if all([res2, res != res2]):
                res = res2
        elif n == 3:
            try:
                check = subprocess.check_output([
                    "dconf", "dump", dcpath + key + "/"
                ]).decode("utf-8")
                if not check:
                    break
            except TypeError:
                break
        n = n + 1 if n < 5 else 0
        # check if mouse is in hotcorner (and wasn't the last time)
        pos = bhc.mousepos()
        if pos:
            corner2 = bhc.get_hot(marge, res)
            if all([corner2, corner2 != corner1]):
                try:
                    action = [a[1] for a in actions if a[0] == corner2 - 1][0]
                except IndexError:
                    pass
                else:
                    try:
                        subprocess.Popen(["/bin/bash", "-c", action])
                    except subprocess.CalledProcessError:
                        pass
            corner1 = corner2


def getkey():
    data = subprocess.check_output([
        "dconf", "dump", dcpath
    ]).decode("utf-8").splitlines()
    try:
        match = [l for l in data if "Hot Corners" in l][0]
        watch = data.index(match) - 3
        return data[watch][1:-1]
    except IndexError:
        pass


# config path
dr = bhc.dr
# settings file
settings = bhc.settings

# try read settings, fallback to defaults if it does not exist
try:
    state_data = ast.literal_eval(open(settings).read().strip())
except FileNotFoundError:
    states = [False, False, False, False]
    entry_data = None
else:
    states = [d[0] for d in state_data]
    entry_data = [d[1] for d in state_data]

# list actions
actions = []
for i in range(len(states)):
    val = states[i]
    if val:
        actions.append([i, entry_data[i]])

# hotcorner = 10 px wide/high
marge = 10

# give dconf a few seconds to create the key
dcpath = "/com/solus-project/budgie-panel/applets/"
time.sleep(3)
key = getkey()

if any(states):
    watch()
