#!/usr/bin/env python3
import sys
import time
import subprocess
import wmovertools as wmt


"""
Budgie WindowMover
Author: Jacob Vlijm
Copyright=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/>.
"""


user = wmt.user


def run_wmover():
    t_res = 20
    res = None
    y_area = 5

    while True:
        if t_res == 20:
            # see if the user is still around
            if user not in subprocess.check_output("who").decode("utf-8"):
                break
            t_res = 0
        # master loop
        time.sleep(0.5)
        # get the current mouse location
        data = wmt.mousepos()
        x = data[0]
        y = data[1]
        if wmt.area(x_area, y_area, xres, yres, x, y, xoffset, yoffset):
            """if mouse is on the right spot,
               check position of the active window
            """
            check_cons = wmt.check_ypos(yres)
            if check_cons[0]:
                # call the mover window
                wmt.callwindow(check_cons[1], xres, yres, xoffset, yoffset)
        t_res = t_res + 1


def singlerun():
    target = wmt.get(["xdotool", "getactivewindow"])
    if target:
        wmt.callwindow(target, xres, yres, xoffset, yoffset)


if __name__ == "__main__":
    resdata = wmt.getres()
    xres = resdata[0]
    yres = resdata[1]
    xoffset = resdata[2]
    yoffset = resdata[3]
    x_area = xres - 110
    try:
        arg = sys.argv[1]
        if arg == "-single":
            singlerun()
        elif arg == "-singlespace":
            wmt.runwindow("none", xres, yres, xoffset, yoffset)

    except IndexError:
        run_wmover()
