#!/usr/bin/env python3
import ast
import subprocess
import time
import bhctools as bhc
import math
import os
import sys


"""
Hot Corners
Author: Jacob Vlijm
Copyright © 2017-2018 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.2
    n = 0
    res = sys.argv[1:]
    res = [int(res[0]), int(res[1])]
    corner1 = None
    user = bhc.user
    poslist = [(0, 0), (0, 0), (0, 0)]
    testpressure = False
    limit = 220

    while True:
        time.sleep(t)
        # check pressure settings once per 5 seconds
        if n == 0:
            testpressure = bhc.get_pressure()
        # check if user is in the house, applet in the panel
        elif n == 12:
            if user not in subprocess.check_output("who").decode("utf-8"):
                break
            try:
                check = subprocess.check_output([
                    "dconf", "dump", dcpath + key + "/"
                ]).decode("utf-8")
                if not check:
                    break
            except TypeError:
                break
        n = n + 1 if n < 25 else 0
        # get the mouse position
        pos = bhc.mousepos()
        # keep also record of speed
        poslist.append(pos)
        poslist = poslist[-3:]
        if pos:
            corner2 = bhc.get_hot(marge, res)
            # check if mouse is in hotcorner (and wasn't the last time)
            if all([corner2, corner2 != corner1]):
                # but first let's check the pressure
                if testpressure:
                    track1 = calc_track(poslist, 0, 1)
                    track2 = calc_track(poslist, 1, 2)
                    if any([track1 >= limit, track2 >= limit]):
                        run_action(corner2)
                else:
                    run_action(corner2)
            corner1 = corner2


def calc_track(poslist, i1, i2):
    xmov = (poslist[i1][0] - poslist[i2][0])**2
    ymov = (poslist[i1][1] - poslist[i2][1])**2
    return math.sqrt(xmov + ymov)


def run_action(corner):
    try:
        action = [a[1] for a in actions if a[0] == corner - 1][0]
    except IndexError:
        pass
    else:
        try:
            subprocess.Popen(["/bin/bash", "-c", action])
        except subprocess.CalledProcessError:
            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 = bhc.getkey(string="Hot Corners")


if any(states):
    watch()
