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

with lib;

let

  cfg = config.service.videoencoder;

  # todo : escape output and input File 
  createEncoder = tmpFolder: inputFile: outputFile: # sh
    ''
      mkdir -p ${tmpFolder}
      rm -rf ${tmpFolder}/*
      TMP_FILE=`mktemp --dry-run ${tmpFolder}/XXXXXXXX.${cfg.format}`

      if [ ! -f "${outputFile}" ]
      then
      ${pkgs.ffmpeg}/bin/ffmpeg \
        -i "${inputFile}" \
        -filter:v scale=h='min(720\,ih)':w='min(1280\,iw)' \
        -vcodec libx264 \
        -preset veryslow \
        -profile:v ${cfg.profile} \
        ${optionalString (cfg.tune != null) "-tune ${cfg.tune}"} \
        -acodec aac \
        "$TMP_FILE" \
        -hide_banner \
        && cp $TMP_FILE "${outputFile}.${cfg.format}" \
        && rm $TMP_FILE
      fi
    '';

in {

  options.service.videoencoder = {
    enable = mkEnableOption "enable service.videoencoder";

    profile = mkOption {
      type = with types; string;
      default = "main";
      description = ''
        -profile:v
      '';
    };

    tune = mkOption {
      type = with types;
        nullOr (enum [ "film" "animation" "grain" "stillimage" ]);
      default = null;
      description = ''
        -tune
      '';
    };

    format = mkOption {
      type = with types; enum [ "mp4" "mkv" ];
      default = "mp4";
      description = ''
        the format
      '';
    };

    fileConfig = mkOption {
      type = with types;
        listOf (submodule {
          options = {
            inputFile = mkOption {
              # todo make this path
              type = with types; string;
              description = ''
                full path to the inputFile
              '';
            };
            outputFile = mkOption {
              type = with types; string;
              description = ''
                full path to the ouputFile
                folder must exist
              '';
            };
          };
        });
      description = ''
        list of files to encode.
      '';
    };
  };

  config = mkIf cfg.enable {

    systemd.services."videoEncoding" = {
      wantedBy = [ "multi-user.target" ];
      enable = true;
      script = let
        myList = map (value:
          createEncoder "/tmp/videoencoder" value.inputFile value.outputFile)
          cfg.fileConfig;
      in ''
        set -x
        ${concatStringsSep "\n" myList}
      '';

    };

  };

}