#!/usr/bin/env python3
import os
import subprocess
import time
import psutil
import wprviews_tools as pv
from set_keys import change_keys
from gi.repository import Gio


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


plugin_path = pv.plugin_path
dcpath = pv.dcpath
ismuted = pv.previews_ismuted
# the backgrounder runs per user
user = pv.user


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


def run_bgrounder():
    # give dconf a few seconds to create the key
    time.sleep(3)
    key = pv.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(ismuted):
            break


# make sure gsettings is ready
time.sleep(5)

settings = Gio.Settings.new("org.ubuntubudgie.plugins.budgie-wpreviews")
if not settings.get_boolean('keybind'):
    change_keys("set_custom")
pid = get_pid()
run_bgrounder()
psutil.Process(pid).terminate()
change_keys("restore")
pv.empty_dir()
