#
# Aura Engine (https://gitlab.servus.at/aura/engine)
#
# Copyright (C) 2017-2020 - The Aura Engine Team.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

in_line_insert_callbacks = ref([])

#####################################
#            FUNCTIONS              #
#####################################

usage_set_track_metadata =
  "set_track_metadata { \"show_name\": \"Analog Ambient\", \"show_id\": 111, \
   \"timeslot_id\": 222, \"playlist_id\": 333, \"playlist_item\": \"\", \
   \"track_type\": 2, \"track_start\": \"2022/02/22 22:02:22\", \
   \"track_duration\": 808.8, \"track_title\": \"Lorem Ipsum\", \"track_album\": \
   \"\", \"track_artist\": \"\" }"

def get_input_line(source_id, device) =
  if
    use_alsa == true
  then
    input.alsa(id=source_id, device=device, bufferize=alsa_buffered_input())
  elsif use_jack == true then input.jack(clock_safe=false, id=source_id)
  else
    input.pulseaudio(id=source_id, client="aura_engine_#{source_id}")
  end
end

input_count = ref(0)

def create_input_line(device) =
  source_id = "line_in_#{input_count}"
  in_line = get_input_line(source_id, device.name)

  # Enable metadata insertion and store callbacks
  in_line = insert_metadata(id=source_id, in_line)
  in_line_insert_callbacks :=
    list.append(
      [("#{source_id}", in_line.insert_metadata)], in_line_insert_callbacks()
    )

  # Old Liquidsoap approach:
  # in_line.on_metadata(on_metadata_notification)
  # New Liquidsoap 2.1 approach, which should not trigger when inactive:
  in_line = source.on_metadata(id=source_id, in_line, on_metadata_notification)
  inputs := list.append([in_line], inputs())

  server.register(
    namespace=source.id(in_line),
    description=
      "Sets the current track metadata for a channel",
    usage=usage_set_track_metadata,
    "set_track_metadata",
    fun (json_string) ->
      begin
        log(
          "Received JSON to set track metadata on channel '#{source_id}' to:\n #{json_string}"
        )
        metadata = build_metadata(json_string)
        insert_callback = list.assoc(source_id, in_line_insert_callbacks())
        insert_callback(metadata)
        "OK"
      end
  )
  input_count := input_count() + 1
end

#####################################
#             SOURCES               #
#####################################

list.iter(create_input_line, config.audio.devices.input)