#
# 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/>.




#####################################
#         CLEAR SOURCE              #
#####################################

def clear_items(ns) =
    ret = server.execute("#{source.id(ns)}.primary_queue")
    ret = list.hd(default="", ret)
    if ret == "" then
        log("Queue cleared.")
        (-1.)
    else
        log("There are still items in the queue, trying skip ...")
        source.skip(ns)
        (0.1)
    end
end

def clear_queue(ns) =
    add_timeout(fast=false, 0.5, {clear_items(ns)})
end


#####################################
#         DYNAMIC SOURCES           #
#####################################

def create_dynamic_source(~skip=true, name)
    log("Creating dynamic source '#{name}'")
    track = get_process_lines("cat "^string.quote("next-track.txt"))
    track = list.hd(default="", track)
    dyn_source = request.dynamic.list(
      { [request.create(track)] })
    dyn_source
end


#####################
# stream to icecast #
#####################

def stream_to_icecast(id, encoding, bitrate, host, port, pass, mount_point, url, description, genre, user, stream, streamnumber, connected, name, channels) =
    source = ref stream

    def on_error(msg)
        connected := "false"
        log(msg)
        5.
    end
    def on_connect()
        connected := "true"
        log("Successfully connected to stream_#{streamnumber}")
    end

    stereo = (int_of_string(channels) >= 2)

    user_ref = ref user
    if user == "" then
        user_ref := "source"
    end

    # Liquidsoap cannot handle one output definition for mono and stereo
    output_icecast_mono   = output.icecast(id = id, host = host, port = port, password = pass, mount = mount_point, fallible = true, url = url, description = description, name = name, genre = genre, user = !user_ref, on_error = on_error, on_connect = on_connect, icy_metadata = "true")
    output_icecast_stereo = output.icecast(id = id, host = host, port = port, password = pass, mount = mount_point, fallible = true, url = url, description = description, name = name, genre = genre, user = !user_ref, on_error = on_error, on_connect = on_connect, icy_metadata = "true")

#    %ifencoder %aac
#    if encoding == "aac" then
#        log("ENABLING AAC to ICECAST")
#        %include "outgoing_streams/aac.liq"
#    end
#    %endif
#
#    %ifencoder %flac
#    if encoding == "flac" then
#        log("ENABLING FLAC to ICECAST")
#        %include "outgoing_streams/flac.liq"
#    end
#    %endif

    if encoding == "mp3" then
        log("ENABLING Mp3 to ICECAST")
        %include "outgoing_streams/mp3.liq"
    end

    if encoding == "ogg" then
        log("ENABLING OGG to ICECAST")
        %include "outgoing_streams/ogg.liq"
    end

#    %ifencoder %opus
#    if encoding == "opus" then
#        log("ENABLING OPUS to ICECAST")
#        %include "outgoing_streams/opus.liq"
#    end
#    %endif
end

###########
# line in #
###########

def set_input(device, name) =
    if use_alsa == true then
        alsa_in = input.alsa(id=name, device=a0_in, clock_safe=false)
        inputs := list.append([alsa_in], !inputs)

    elsif use_jack == true then
        jack_in = input.jack(id=name, clock_safe=false)
        inputs := list.append([jack_in], !inputs)

    else
        pulse_in = input.pulseaudio(id=name, client="AuraEngine Line IN")
        inputs := list.append([pulse_in], !inputs)
    end
end

############
# line out #
############

def get_output(source, device, name) =
    if device != "" then
        if use_alsa == true then
            log("--- Set ALSA Output ---")
            if device == "default" then
                output.alsa(id="lineout", source)
            else
                output.alsa(id=name, device=device, source)
            end
        elsif use_jack == true then
            log("--- Set JACK AUDIO Output ---")
            output.jack(id=name, source)
        else
            log("--- Set PULSE AUDIO Output ---")
            output.pulseaudio(id=name, client="AuraEngine Line OUT", source)
        end
    else
        log("OUTPUT DUMMY")
        output.dummy(id=name^"_DUMMY", blank())
    end
end