import subprocess
from i3pystatus import IntervalModule, formatp


class ArchUpdates(IntervalModule):

    settings = (
        "format",
        "format_down",
        "color",
    )

    interval = 60
    format = "Update count: {count_pacman} {count_yaourt}"
    format_down = ""
    color = "#FFFFFF"

    # clicking on it after installing updates will dismiss the notification
    on_leftclick = "run"

    def run(self):
        # We updates the db
        command = ["sudo", "yaourt", "-Sya"]
        subprocess.Popen(command, stdout=subprocess.PIPE,
                         stderr=subprocess.DEVNULL)

        count_pacman = self.get_count(["yaourt", "-Qu"])
        count_yaourt = self.get_count(["yaourt", "-Qua"])

        format = self.format if count_yaourt else self.format_down
        count_yaourt -= count_pacman

        fdict = {
            "count_pacman": count_pacman,
            "count_yaourt": count_yaourt,
        }

        self.output = {
            "full_text": formatp(format, **fdict).strip(),
            "color": self.color,
        }
        return

    def get_count(self, command):
        check_pacman = subprocess.Popen(command, stdout=subprocess.PIPE,
                                        stderr=subprocess.DEVNULL)
        output = check_pacman.communicate()[0].decode("UTF-8").strip()
        return len(output.split("\n")) if len(output) > 0 else 0