#!/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:
        # check/update screen resolution once per 10 seconds
        if t_res == 20:
            # ...and see if the user is still around
            if user not in subprocess.check_output("who").decode("utf-8"):
                break
            res2 = wmt.getres()
            if all([res2, res2 != res]):
                xres = res2[0]
                yres = res2[1]
                x_area = xres - 110
                res = res2
            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):
            """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)
        t_res = t_res + 1


def singlerun(resdata):
    target = wmt.get(["xdotool", "getactivewindow"])
    if target:
        wmt.callwindow(
            target,
            resdata[0],
            resdata[1],
        )


if __name__ == "__main__":
    try:
        arg = sys.argv[1]
        resdata = wmt.getres()
        if arg == "-single":
            singlerun(resdata)
        elif arg == "-singlespace":
            wmt.runwindow("none", resdata[0], resdata[1])
    except IndexError:
        run_wmover()
