{ lib, config, pkgs, ... }:
let
  util = import ../util pkgs;
  inherit (util) nullable;
  inherit (util.fn) compose;
  inherit (util.str) concat;
  inherit (lib) types mkEnableOption mkOption mkIf concatStringsSep concatStrings;

  cfg = config.services.swaybg;
in {
  options.services.swaybg = {
    enable = mkEnableOption "swaybg";
    color = mkOption {
      description = "Background color [rrggbb]";
      type = with types; nullOr str;
      default = null;
    };
    image = mkOption {
      description = "Path to wallpaper";
      type = with types; nullOr path;
      default = null;
    };
    mode = mkOption {
      description = "[stretch|fill|fit|center|tile|solid_color]";
      type = types.str;
      default = "fill";
    };
    output = mkOption {
      description = "Output monitor";
      type = with types; nullOr (listOf str);
      default = null;
    };
  };

  config = mkIf cfg.enable {
    home.packages = [ pkgs.swaybg ];
    systemd.user.services.swaybg = {
      Unit = {
        Description = "Swaybg wallpaper daemon";
        PartOf = [ "graphical-session.target" ];
        After = [ "graphical-session.target" ];
      };
      Install.WantedBy = [ "graphical-session.target" ];
      Service.ExecStart = concatStringsSep " " [
        "${pkgs.swaybg}/bin/swaybg"
        (if cfg.color == null then "" else "--color ${cfg.color}")
        (if cfg.image == null then "" else "--image ${cfg.image}")
        "--mode ${cfg.mode}"
        (nullable.map (compose concatStrings <| map <| concat " --output ") cfg.output |> nullable.default "")
      ];
    };
  };
}