/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*-  */
/*
 * main.cc
 * Copyright (C) 2014 John Coppens <john@jcoppens.com>
 * 
 * socket_test is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * socket_test 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <gtk/gtk.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#include "config.h"
#include "fifocom.h"


#ifdef ENABLE_NLS
#  include <libintl.h>
#endif

// For testing propose use the local (not installed) ui file 
// #define UI_FILE PACKAGE_DATA_DIR"/ui/socket_test.ui" 
#define UI_FILE "src/socket_test.ui"

#define FIFO_ROOT "fifo"

GtkWidget       *MainWindow;
GtkTextBuffer   *txtbuffer;

// Note: For some strange reason the 'extern "C"' is necessary to define
// handlers for the gtk_builder_connect_signals() call - and only if
// g++ is used!

extern "C" gboolean
quit_button_clicked_cb(GtkButton *btn)
{
  gtk_main_quit();
}

extern "C" void
on_main_window_delete_event(GtkWidget *w)
{
  gtk_main_quit();
}

extern "C" void
tx_entry_activate(GtkEntry *entry)
{
  write_chars(channel, (char *) gtk_entry_get_text(entry));
  write_chars(channel, (char *) "\n");
  gtk_entry_set_text(entry, "");
}


void
add_to_textbuffer(char *message)
{
  GtkTextIter iter;
  
  gtk_text_buffer_get_end_iter(txtbuffer, &iter);
  gtk_text_buffer_insert(txtbuffer, &iter, message, strlen(message));
}

int
main (int argc, char *argv[])
{
  GtkWidget *txtview;
  GError *error = NULL;
  int listenfd;
	
  gtk_init(&argc, &argv);

  GtkBuilder *builder = gtk_builder_new();

  gtk_builder_add_from_file(builder, UI_FILE, &error);
  gtk_builder_connect_signals(builder, NULL);
	
  // Get references to some of the widgets we use frequently
  MainWindow = GTK_WIDGET(gtk_builder_get_object(builder, "main_window"));
  txtview    = GTK_WIDGET(gtk_builder_get_object(builder, "textview1"));
  MainWindow = GTK_WIDGET(gtk_builder_get_object(builder, "tx_entry"));
  
  // 'Manually' create a textbuffer and connect it to the textview
  txtbuffer = gtk_text_buffer_new(NULL);
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(txtview), txtbuffer);
  
  g_object_unref(G_OBJECT(builder));		// Don't need the builder anymore

  gtk_widget_show_all(MainWindow);		// Queue drawing all widgets
	
  start_comm(FIFO_ROOT, add_to_textbuffer);
	
  gtk_main();
	
  close_comm();

  return 0;
}