#!/usr/bin/env python

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

# Available Updates holders
avail = ""
# pkgList = ""
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)
    global avail
    avail = str(outputCount)+" Updates"
    tray.setToolTip(avail)
    for i in outputList.splitlines():
        menu.addAction(i, functools.partial(infos, i))
    
# 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():
    for i in outputList.splitlines():
        menu.removeAction(i)

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

# Set up timer to update count
timer = QTimer()
timer.timeout.connect(clear)
timer.timeout.connect(count)
timer.singleShot(1,count) # Initially populate available updates
timer.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_()