/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*-  */
/*
 * main.cc
 * Copyright (C) 2014 John Coppens <root@on6jc>
 * 
 * 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 "socketcom.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 TCP_HOST "127.0.0.1"
#define TCP_PORT 5000 

GtkWidget *MainWindow,
	  *entry;
GtkTextBuffer *txtbuffer;


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)
{
  network_write_chars(channel, (char *) gtk_entry_get_text(entry));
  network_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);
	
  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"));
  
  txtbuffer = gtk_text_buffer_new(NULL);
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(txtview), txtbuffer);
  
  g_object_unref(G_OBJECT(builder));

  gtk_widget_show_all(MainWindow);
	
  start_socket(TCP_HOST, TCP_PORT, add_to_textbuffer);
	
  gtk_main();
	
  close_socket(listenfd);

  return 0;
}