#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <gst/gst.h>



static char *prefix = "YOUR PATH";

#define NUM_TRACKS 13
static char *songs[13] = {"YOUR FILE 1",
                          "YOUR FILE 2" };


int set_uri(GstElement *playbin, char *filename)
{
    GError *err = NULL;
    gchar *uri = gst_filename_to_uri(filename, &err);
    if (!uri) {
        printf("Unable to allocate the uri\n");
        return -1;
    }
    g_object_set(playbin, "uri", uri, NULL);
    g_free(uri);
    return 0;
}

void about_to_finish(GstElement *playbin, gpointer user_data)
{
    static int song_index = 1;
    char filename[128];

    memset(filename, 0, sizeof(filename));
    snprintf(filename, sizeof(filename), "%s%s", prefix, songs[song_index]);
    printf("about to finish, queue %s\n", songs[song_index]);
    if (set_uri(playbin, filename)) {
        printf("Unable to set the uri in about-to-finish\n");
    }

    song_index = (song_index + 1) % NUM_TRACKS;
}

GstElement *create_audio_bin()
{
    GstElement *bin = gst_bin_new("audio_bin");
    GstElement *sink = gst_element_factory_make("fakesink", NULL);

    if(!sink) {
        gst_object_unref(bin);
        return NULL;
    }

    gst_bin_add(GST_BIN(bin), sink);

    GstPad *pad = gst_element_get_static_pad(sink, "sink");
    gst_element_add_pad(bin, gst_ghost_pad_new("sink", pad));
    gst_object_unref(GST_OBJECT(pad));


    return bin;
}

int main(int argc, char *argv[])
{
    struct stat sb;

    gst_init(NULL, NULL);
    GstElement *playbin = gst_element_factory_make("playbin", NULL);
    if (!playbin) {
        printf("unable to create playbin\n");
        goto out;
    }

    char filename[128];
    GstElement *audio_sink_bin = create_audio_bin();

    if (!audio_sink_bin) {
        goto out;
    }

    g_object_set(playbin, "audio-sink", audio_sink_bin, NULL);
    memset(filename, 0, sizeof(filename));
    snprintf(filename, sizeof(filename), "%s%s", prefix, songs[0]);
    if (set_uri(playbin, filename)) {
        goto out;
    }

    g_signal_connect(playbin, "about-to-finish", G_CALLBACK(about_to_finish), NULL);
    gst_element_set_state(playbin, GST_STATE_PLAYING);

    while (1) {
        memset(&sb, 0, sizeof(sb));
        if (!stat("stop", &sb)) {
            unlink("stop");
            break;
        }
        sleep(15);
    }
    gst_element_set_state(playbin, GST_STATE_NULL);
    gst_element_get_state(playbin, NULL, NULL, GST_CLOCK_TIME_NONE);
    gst_object_unref(playbin);
out:
    gst_deinit();
    return 0;
}
