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

  sonoffSwitches = {
    #"pal01" = {
    #  label = "Schlafzimmer Lampe Links";
    #  icon = "mdi:lightbulb";
    #  groups = [ "bed_room" ];
    #};
    "pal02" = {
      label = "Drucker / Scanner";
      icon = "mdi:printer";
      groups = [ "bed_room" "today" ];
    };
    #"pal03" = {
    #  label = "Wohnzimmer Lampe";
    #  icon = "mdi:lightbulb";
    #  groups = [ "living_room" ];
    #};
    #"pal04" = {
    #  label = "Schlafzimmer Lampe Rechts";
    #  icon = "mdi:lightbulb";
    #  groups = [ "bed_room" ];
    #};
    "pal05" = {
      label = "TV";
      icon = "mdi:television";
      groups = [ "tv" ];
      device = "tv";
    };
    #"pal06" = {
    #  label = "Küchen Lampe";
    #  icon = "mdi:lightbulb";
    #  groups = ["kitchen_room"];
    #};
    "pal07" = { label = "Nummer 7"; };
    "pal08" = { label = "Nummer 8"; };
  };

  toSwitch = name: "switch.${name}";

in {

  imports = [ ./mqtt.nix ];

  services.homeAssistantConfig = {

    # nicer names
    # -----------
    homeassistant.customize = lib.mapAttrs' (entity:
      { label, icon ? "mdi:power-plug-off", ... }: {
        name = toSwitch entity;
        value = {
          friendly_name = label;
          icon = icon;
        };
      }) sonoffSwitches;

    # define switches
    # ---------------
    switch = lib.mapAttrsToList (name:
      { ... }: {
        name = name;
        platform = "mqtt";
        command_topic = "cmnd/${lib.toUpper name}/POWER";
        state_topic = "stat/${lib.toUpper name}/POWER";
        payload_on = "ON";
        payload_off = "OFF";
        state_on = "ON";
        state_off = "OFF";
      }) sonoffSwitches;

    # discover state on init
    # ----------------------
    automation = [{
      alias = "Sonoff initial Power state";
      trigger = {
        platform = "homeassistant";
        event = "start";
      };
      action = lib.mapAttrsToList (name:
        { ... }: {
          service = "mqtt.publish";
          data = {
            topic = "cmnd/${lib.toUpper name}/power";
            payload = "";
          };
        }) sonoffSwitches;
    }];

    # append to groups
    # ----------------
    group = let
      # sort lights into given groups.
      sortedInGroups = let
        groupEntries = lib.zipAttrs (lib.flatten (lib.mapAttrsToList (name:
          { groups ? [ ], ... }:
          map (groupName: { "${groupName}" = "switch.${name}"; }) groups)
          sonoffSwitches));
      in lib.mapAttrs (name: entities: { inherit entities; }) groupEntries;
    in sortedInGroups;
  };

}