#!/usr/bin/env python

# Get needed modules
import yaml
import webbrowser
import subprocess
from os import path
from time import sleep
from functools import partial
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# Available Updates holders
avail = ""
outputList = ""

# Use config.yml file to allow for compatibility with
# most terminal emulators possible & custom icon / timer duration
with open(path.expanduser("~/.config/systrayUpdater/systrayUpdater.yml")) as f:
    conf = yaml.load(f, yaml.FullLoader)
    term = str(conf['terminal'])
    opt = str(conf['option'])
    wait = int(conf['timer']) * 60000
    icn = path.join(path.expanduser("~/.config/systrayUpdater/"), str(conf['icon']))
    f.close()

# Run checkupdates command
# Populates the available updates and count
# Sets the list and count in proper spots
def count():
    cmd = ['checkupdates']
    p1 = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    global outputList
    outputList = ((p1.communicate()[0]).decode()).rstrip('\n')
    outputCount = len(outputList.splitlines())
    if outputCount == 0:
        tray.setVisible(False)
    else:
        tray.setVisible(True)
        for i in outputList.splitlines():
            menu.addAction(i, partial(infos, i))
        global avail
        avail = str(outputCount)+" Updates"
        tray.setToolTip(avail)
    
# Run system update
def update():
    cmd = [ term, opt, 'sudo', 'pacman', '-Syu' ]
    subprocess.Popen(cmd)

# Get pkg info
def infos(pkgString):
    pkg = pkgString.split(' ')
    url = 'https://archlinux.org/packages/?q='+ pkg[0]
    webbrowser.open_new_tab(url)

# Clear old update list when new list available
def clear():
    menu.clear()
    menu.addAction(option1)
    menu.addAction(quit)


# Create an app surface
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

# Set up timer to update count
clearTimer = QTimer()
clearTimer.timeout.connect(clear)
updateTimer = QTimer()
updateTimer.timeout.connect(count)
updateTimer.singleShot(1,count) # Initially populate available updates
clearTimer.start(wait)
sleep(1)
updateTimer.start(wait)

# Adding items to the menu 
tray = QSystemTrayIcon()
icon = QIcon(icn)
tray.setIcon(icon)
tray.setToolTip(avail)
tray.setVisible(True)

# Creating the options
menu = QMenu()
option1 = QAction("Run Update")
option1.triggered.connect(update)
option1.triggered.connect(count)
menu.addAction(option1)

# To quit the app
quit = QAction("Quit")
quit.triggered.connect(app.quit)
menu.addAction(quit)

# Place the app in the System Tray
tray.setContextMenu(menu)

app.exec_()