#!/usr/bin/env python3
import os
import subprocess
import time
import psutil
from budgie_wswitcher import wswitcher_ismuted, user

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

ismuted = wswitcher_ismuted


def get_pid():
    app = os.path.dirname(os.path.abspath(__file__)) + "/wswitcher_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 "Wallpaper Switcher" in l][0]
        watch = data.index(match) - 3
        return data[watch][1:-1]
    except IndexError:
        pass


def run_wswitcher():
    # 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(ismuted):
            break


dcpath = "/com/solus-project/budgie-panel/applets/"
pid = get_pid()
run_wswitcher()


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