#include <gst/gst.h>

gint counter = 0;

static void
bus_message (GstBus * bus, GstMessage * message,
    gpointer data)
{
  GError *err = NULL;
  gchar *debug;
  GMainLoop *loop = data;

  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_ERROR:
      gst_message_parse_error (message, &err, &debug);
      gst_object_default_error (GST_MESSAGE_SRC (message), err, debug);
      g_error_free (err);
      g_free (debug);
      g_assert_not_reached ();
      break;
    case GST_MESSAGE_WARNING:
      gst_message_parse_warning (message, &err, &debug);
      gst_object_default_error (GST_MESSAGE_SRC (message), err, debug);
      g_error_free (err);
      g_free (debug);
      //g_assert_not_reached ();
      break;
    case GST_MESSAGE_EOS:
      g_main_loop_quit (loop);
      break;
    default:
      break;
  }
}

static gboolean
start_capture (gpointer data)
{
  gchar *fn;

  fn = g_strdup_printf ("test_%d.mov", counter++);
  g_print ("Starting capture\n");
  g_object_set (data, "filename", fn, NULL);
  g_signal_emit_by_name (data, "capture-start", NULL);
  g_free (fn);

  return FALSE;
}

static gboolean
reset_state (gpointer data)
{
  g_print ("Reset state\n");
  gst_element_set_state (GST_ELEMENT (data), GST_STATE_NULL);
  gst_element_set_state (GST_ELEMENT (data), GST_STATE_PLAYING);

  return FALSE;
}

static gboolean
stop_capture (gpointer data)
{
  g_print ("Stopping capture\n");
  g_signal_emit_by_name (data, "capture-stop", NULL);

  return FALSE;
}

static gboolean
change_profile (gpointer data)
{
  GstElement *camerabin = GST_ELEMENT (data);

  GstElement *mux;
  GstElement *venc;
  GstElement *aenc;

  mux = gst_element_factory_make ("qtmux", NULL);
  venc = gst_element_factory_make ("x264enc", NULL);
  aenc = gst_element_factory_make ("faac", NULL);

  g_object_set (camerabin, "video-muxer", mux, "video-encoder", venc,
      "audio-encoder", aenc, NULL);
  return FALSE;
}

int main() {
  GstElement *camera;
  GstBus *bus;
  GMainLoop *loop;

  gst_init (NULL, NULL);

  loop = g_main_loop_new (NULL, FALSE);

  camera = gst_element_factory_make ("camerabin", NULL);
  g_object_set (camera, "mode", 1, NULL);
  g_object_set (camera, "flags", 0xdf, NULL);
  g_signal_emit_by_name (camera, "set-video-resolution-fps", 320, 240, 30000, 1001, NULL);

  bus = gst_pipeline_get_bus (camera);
  gst_bus_add_watch (bus, bus_message, loop);
  gst_object_unref (bus);

  change_profile (camera);

  g_timeout_add_seconds (10, start_capture, camera);
  g_timeout_add_seconds (25, stop_capture, camera);

  g_timeout_add_seconds (40, start_capture, camera);
  g_timeout_add_seconds (60, stop_capture, camera);
  g_timeout_add_seconds (80, g_main_loop_quit, loop);

  gst_element_set_state (camera, GST_STATE_PLAYING);
  g_main_loop_run (loop);
  gst_element_set_state (camera, GST_STATE_NULL);

  gst_object_unref (camera);
  g_main_loop_unref (loop);
  return 0;
}
