{
  config,
  lib,
  namespace,
  pkgs,
  ...
}:
let
  cfg = config.${namespace}.programs.waybar;

  waybar-notifications = pkgs.writeScriptBin "waybar-notifications" ''
    #!/usr/bin/env python

    import subprocess
    import json
    import codecs
    import re

    def check_notifications(args = "history"):
        notifications = []
        number = None
        content = None
        appname = None
        urgency = None
        cmd = "makoctl"
        temp = subprocess.Popen([cmd, args], stdout = subprocess.PIPE)
        output = str(temp.communicate()).replace("(b\'", "").replace("\', None)", "")
        lines = output.split("\\n")
        for line in lines:
            if "Notification" in line:
                number = line.split(":")[0].replace("Notification ", "")
                content = re.sub(r"[\u2066\u2067\u2068\u2069, \u00e2\u0081\u00a8]", "", codecs.decode(line.split(": ")[-1].encode("latin1").decode("utf-8"), "unicode_escape"))
                content = re.sub(r"[\u00a9]", " ", content)

            if "App name" in line:
                appname = line.split(": ")[-1]
            if "Urgency" in line:
                urgency = line.split(": ")[-1]
            
            if number is not None and content is not None and appname is not None and urgency is not None:
                notifications.append((number, content, appname, urgency))
                number = None
                content = None
                appname = None
                urgency = None

        return notifications

    def get_icon(notifications):
        status = ""
        icon = ""

        for number, content, appname, urgency in notifications:
            status = "notify"
            if urgency != "normal":
                status = "alert"
                break

        if status == "notify":
            icon = "󰂞"
        if status == "alert":
            icon = "󰵙"

        return icon, status

    def build_tooltip(notifications):
        tooltip = ""
        for number, content, appname, urgency in notifications:
            tooltip += "{0}: {1}\n".format(appname, content)

        return tooltip

    def main():
        notifications = check_notifications()
        data = {}

        icon, status = get_icon(notifications)

        data["text"] = icon
        data["tooltip"] = build_tooltip(notifications)
        data["class"] = status

        print(json.dumps(data, ensure_ascii=False))

    main()

  '';
in
{
  imports = [ ../options.nix ];

  config = lib.mkIf cfg.enable {
    home.packages = [ waybar-notifications ];
  };
}
