#!/usr/bin/env python3
import os
import subprocess
import time

import psutil

import wmovertools as wmt
from set_keys import change_keys

"""
Budgie Window Mover
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/>.
"""


dcpath = "/com/solus-project/budgie-panel/applets/"
appletpath = wmt.appletpath
wmover_ismuted = wmt.wmover_ismuted
user = wmt.user


def get_pid():
    app = os.path.join(appletpath, "wmover_run")
    try:
        return int(subprocess.check_output([
            "pgrep", "-f", "-u", user, app,
        ]).decode("utf-8").strip())
    except subprocess.CalledProcessError:
        return subprocess.Popen(app).pid


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


def run_wmover():
    # give dconf a few seconds to create the key
    time.sleep(3)
    key = getkey()
    while True:
        time.sleep(3)
        try:
            check = subprocess.check_output([
                "dconf", "dump", dcpath + key + "/",
            ]).decode("utf-8")
            login = user in subprocess.check_output("who").decode("utf-8")
            if not all([check, login]):
                break
        except TypeError:
            break
        if os.path.exists(wmover_ismuted):
            break


change_keys("set_custom")
pid = get_pid()
run_wmover()


try:
    psutil.Process(pid).terminate()
except psutil.NoSuchProcess:
    pass


change_keys("restore")
