/* Copyright (c) 2005-2008 DN-Systems GmbH http://rfdump.org

This program 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 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */

/* $Header: /cvs/rfdump/src/callbacks.c,v 1.21 2008/02/01 19:45:36 dirk Exp $ */

#include <ctype.h>
#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "main.h"
#include "xml.h"

GtkWidget *windowPreferences;
GtkWidget *windowAbout;

void updateGUI(int adr, gchar *new_text);

void on_quit1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  gtk_main_quit();
  exit(1);
}

static char *last_fn="rfd.xml";
void on_save1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  GtkWidget *dialog;
  dialog = gtk_file_chooser_dialog_new("Save File",
				       GTK_WINDOW(windowRFDump),
				       GTK_FILE_CHOOSER_ACTION_SAVE,
				       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
				       GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
				       NULL);
  gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
  gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), last_fn);

  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    {
      char *fn = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
      g_assert(fn);

      /* check for suffix */
      const int len=strlen(fn);
      if(len<5 || fn[len-4]!='.' || fn[len-3]!='x' || fn[len-2]!='m' || fn[len-1]!='l')
	{
	  char *fn_=g_strdup_printf("%s.xml", fn);
	  g_free(fn);
	  fn=fn_;
	}

      xmlWriteTag(&tag, fn);
      last_fn=fn;
    }

  gtk_widget_destroy (dialog);
}


void on_load1_activate (GtkMenuItem *menuitem, gpointer user_data)
{
  stop_scan();

  char *filename=0;
  GtkWidget *dialog;
  dialog = gtk_file_chooser_dialog_new("Open File",
				       GTK_WINDOW(windowRFDump),
				       GTK_FILE_CHOOSER_ACTION_OPEN,
				       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
				       GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
				       NULL);

  GtkFileFilter *filt=gtk_file_filter_new();
  g_assert(filt);
  gtk_file_filter_add_pattern(filt, "*.xml");
  gtk_file_chooser_set_filter(GTK_FILE_CHOOSER (dialog), filt);

  gtk_file_chooser_set_filename(GTK_FILE_CHOOSER (dialog), last_fn);

  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
  gtk_widget_destroy (dialog);

  if(!filename)
    return;

  xmlReadTag(&tag, filename);
  last_fn=filename;

  setup_table();
}


void on_about1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  gtk_widget_show(windowAbout);
}

static gboolean prefs_from_checkbox(char *id)
{
  gboolean b=FALSE;
  GtkWidget *w=GTK_WIDGET (gtk_builder_get_object (builder, id));
  if(w)
    {
      b=gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w));
      g_key_file_set_boolean(prefs, PREFS_GROUP, id, b);
    }
  else
    fprintf(stderr, "could not find Widget %s\n", id);

  return b;
}

static const gchar* prefs_from_entry(char *id)
{
  const gchar *str=0;
  GtkWidget *w=GTK_WIDGET (gtk_builder_get_object (builder, id));
  if(w)
    {
      str=gtk_entry_get_text(GTK_ENTRY(w));
      g_key_file_set_value(prefs, PREFS_GROUP, id, str);
    }
  else
    fprintf(stderr, "could not find Widget %s\n", id);

  return str;
}

void on_preferencesSaved_clicked(GtkButton *button, gpointer user_data)
{
  int i;

  use_cookies = prefs_from_checkbox(PREFS_COOKIE_ACTIVE);

  GtkWidget *tfCookieID = GTK_WIDGET (gtk_builder_get_object (builder, PREFS_COOKIE)); g_assert(tfCookieID);
  cookie_id = (gchar*)gtk_entry_get_text(GTK_ENTRY(tfCookieID));
  for(i=0; i<strlen(cookie_id); ++i)
    if(!isxdigit(cookie_id[i]))
      cookie_id[i]='0';
  g_key_file_set_value(prefs, PREFS_GROUP, PREFS_COOKIE, cookie_id);

  init_reader_arg a;
  a.readerdevice = prefs_from_entry(PREFS_ACG_SERIALPORT);
  a.baudrate = prefs_from_entry(PREFS_ACG_BAUDRATE);
  a.binarymode = prefs_from_checkbox(PREFS_ACG_BINARYMODE);

  writePreferences();
  gtk_widget_hide(windowPreferences);
  poll_gtk();

  if(a.readerdevice && a.baudrate)
    init_reader(&a);
}


void on_preferencesCancel_clicked(GtkButton *button, gpointer user_data)
{
  gtk_widget_hide(windowPreferences);
}

static void entry_from_prefs(char *id)
{
  char *str=g_key_file_get_value(prefs, PREFS_GROUP, id, NULL);
  if(str)
    {
      GtkWidget *w=GTK_WIDGET (gtk_builder_get_object (builder, id));
      if(w)
	gtk_entry_set_text(GTK_ENTRY(w), str);
      else
	fprintf(stderr, "could not find Widget %s\n", id);
    }
}

static void checkbox_from_prefs(char *id)
{
  gboolean b=g_key_file_get_boolean(prefs, PREFS_GROUP, id, NULL);
  GtkWidget *w=GTK_WIDGET (gtk_builder_get_object (builder, id));
  if(w)
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), b);
  else
    fprintf(stderr, "could not find Widget %s\n", id);
}

void on_preferences1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  checkbox_from_prefs(PREFS_COOKIE_ACTIVE);

  entry_from_prefs(PREFS_COOKIE);
#if 0
  GtkWidget *tfCookieID = GTK_WIDGET (gtk_builder_get_object (builder, "tfCookieID")); g_assert(tfCookieID);
  gtk_entry_set_text(GTK_ENTRY(tfCookieID), cookie_id);
#endif
  entry_from_prefs(PREFS_ACG_SERIALPORT);
  entry_from_prefs(PREFS_ACG_BAUDRATE);
  checkbox_from_prefs(PREFS_ACG_BINARYMODE);

  gtk_widget_show(windowPreferences);
}


void on_btAboutOK_clicked(GtkButton *button, gpointer user_data)
{
  gtk_widget_hide(windowAbout);
}

void on_start_scan1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  start_scan();
}


void on_stop_scan1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  stop_scan();
}

void on_clear1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  tag_clear(&tag);
  gtk_entry_set_text((GtkEntry*)entryTagID, "");
  gtk_entry_set_text((GtkEntry*)entryTagType, "");
  gtk_entry_set_text((GtkEntry*)entryManufacturer, "");
  gtk_list_store_clear((GtkListStore*)model);
}

void on_write_all_pages1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  char line[255];
  if(rfidSelect(fd, line, sizeof(line)) < 0)
    {
      error_dialog("Could not Select a tag. Maybe no tag is present near the Reader?");
      return;
    }

  char id[255];
  rfidGetTagID(line, id);

  if(rfidWriteAllPages(fd, &tag) < 0)
    {
      error_dialog("Could not Write All Pages.");
      return;
    }

  start_scan();
}

void on_reset1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  rfidReset(fd);
}

void on_set_to_defaults1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  stop_scan();
  if(rfidReaderSetup(fd) < 0)
    {
      error_dialog("Could not setup RFID reader.");
      exit(1);
    }
  if(rfidReaderInfo)
    rfidReaderInfo(fd);
}

void on_search_baud_rate1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  stop_scan();
  int br=search_baud_rate();
  if(br>0)
    {
      // TODO: save baudrate to preferences

      char buf[128];
      snprintf(buf, sizeof(buf), "Found Reader with %i baud", br);
      info_dialog(buf);

      start_scan();
    }
}

void on_show_settings1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
  stop_scan();
  if(rfidReaderInfo)
    rfidReaderInfo(fd);
}
