#!/usr/bin/env python3
import os
import subprocess
import time
import psutil
from clocktools import app_path, user

"""
Budgie ShowTime
Author: Jacob Vlijm
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/"
app = os.path.join(app_path, "ShowTime")


def getkey():
    # get the specific dconf path, referring to the applet's key
    data = subprocess.check_output([
        "dconf", "dump", dcpath,
    ]).decode("utf-8").splitlines()
    try:
        match = [l for l in data if "ShowTime" in l][0]
        watch = data.index(match) - 3
        return data[watch][1:-1]
    except IndexError:
        pass


def get_pid():
    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_showtime():
    # give dconf a few seconds to create the key
    time.sleep(3)
    key = getkey()
    while True:
        time.sleep(3)
        try:
            # ok, ok, this should be fetched with help from wmovertools...
            check = subprocess.check_output([
                "dconf", "dump", dcpath + key + "/",
            ]).decode("utf-8")
            if not check:
                break
        except TypeError:
            break


pid = get_pid()
run_showtime()
psutil.Process(pid).terminate()
