{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.programs.khal;

  notificationScript = pkgs.writeShellApplication {
    name = "khal-notification";

    runtimeInputs = [
      pkgs.coreutils-full
      pkgs.khal
      pkgs.libnotify
      pkgs.gnugrep
    ];

    text = ''
      date=$(date "+%H:%M:00")
      events=$(khal list -d contact_birthdays -d typo3 --notstarted "$date" "$1" | (grep -v -e "Urlaub" -e "Today"; true))
      if [ -z "$events" ]; then
        exit 0;
      fi

      notify-send \
        --urgency=critical \
        --expire-time=90000 \
        --icon="${config.gtk.iconTheme.package}/share/icons/${config.gtk.iconTheme.name}/32/apps/office-calendar.svg" \
        --category="x-custom.calendar.event" \
        "Upcoming Events" \
        "$events"
      exit 0
    '';
  };

in {
  options.programs.khal = {
    notificationFrequency = mkOption {
      type = types.str;
      default = "*:0/15";
      example = "hourly";
      description = ''
          The notification frequency.
          Check <literal>man systemd.time</literal> for more information on the syntax.
      '';
    };

    notificationTimeDelta = mkOption {
      type = types.str;
      default = "15m";
      example = "15m";
      description = "The delta to pass to khal list.";
    };
  };

  config = mkIf cfg.enable {
    systemd.user.services.khal_notification = {
      Unit = { Description = "khal notification"; };
      Service = { ExecStart = "${notificationScript}/bin/khal-notification \"${cfg.notificationTimeDelta}\""; };
    };

    systemd.user.timers.khal_notification = {
      Unit = { Description = "khal notification"; };
      Timer = {
        OnCalendar = "${cfg.notificationFrequency}";
        Unit = "khal_notification.service";
      };
      Install = { WantedBy = [ "timers.target" ]; };
    };
  };
}
