/** -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: sw=4:ts=4:
 *
 * Gnome Apt frontend
 *
 * 	(C) 1998 Havoc Pennington <hp@pobox.com>
 * 	    1999 Diego Delgado Lages <dlages@dcc.ufrj.br>
 * 	         Olivier Aubin <ogaubin@ucalgary.ca>
 * 	    2002, 2003 Filip Van Raemdonck <mechanix@debian.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * 	$Id$
 *
 **/

#include <apt-pkg/configuration.h>
#include <gtk/gtktreeview.h>

#include "gnome-apt.h"
#include "rsources.h"
#include "sources.h"
#include "sources-wizard.h"

enum {
	C_STATUS,
	C_TYPE,
	C_URI,
	C_DIST,
	C_SECT,
	C_RECORD,
	N_COLS
};

Sources::Sources (void) : src_list(0), selection(0), b_add_(0), b_del_(0), b_edit_(0),
      edit_dialog_dist_(0), edit_dialog_uri_(0), edit_dialog_section_(0) {
	/* Nothing to do */
}

static void
response_cb (GtkWidget* wdg, gint response, gpointer data) {
	Sources* src = static_cast<Sources*> (data);

	if (response == GTK_RESPONSE_APPLY) {
		src->apply (wdg);
	} else if (response == GTK_RESPONSE_OK) {
		src->apply (wdg);
		src->close (wdg);
	} else if (response != GTK_RESPONSE_CANCEL && response != GTK_RESPONSE_DELETE_EVENT) {
		g_warning ("Got response: %d", response);
		src->close (wdg);
	} else {
		src->close (wdg);
	}
}

static void
row_activated_cb (GtkTreeView* tree, GtkTreePath* path, GtkTreeViewColumn* col, gpointer data) {
	Sources* src = static_cast<Sources*> (data);

	GtkWidget* win = gtk_widget_get_toplevel (GTK_WIDGET (tree));
	if (!GTK_WIDGET_TOPLEVEL (win)) {
		win = NULL;
	}
	src->edit_source (win);
}

void 
Sources::edit()
{
	src_list = new SourcesList;

	if (!src_list->ReadSources()) {
		GtkWidget* dialog = gtk_message_dialog_new (
			NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR,
			GTK_BUTTONS_CLOSE, _("The list of sources could not be read."));
      gnome_apt_setup_dialog(dialog);
		gtk_dialog_run (GTK_DIALOG (dialog));

		gtk_widget_destroy (dialog);
		delete src_list;
		src_list = 0;

      return;
    }
	if (!src_list->ReadVendors()) {
		GtkWidget* dialog = gtk_message_dialog_new (
			NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR,
			GTK_BUTTONS_CLOSE, _("The list of vendor keys could not be read."));
		gnome_apt_setup_dialog (dialog);
		gtk_dialog_run (GTK_DIALOG (dialog));

		gtk_widget_destroy (dialog);
		delete src_list;
		src_list = 0;

		return;
	}

	GtkWidget* src_dialog = gtk_dialog_new_with_buttons (_("Gnome-Apt Repository List"),
	      NULL, GTK_DIALOG_DESTROY_WITH_PARENT,
	      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
	      GTK_STOCK_APPLY, GTK_RESPONSE_APPLY,
	      GTK_STOCK_OK, GTK_RESPONSE_OK, NULL);
	gtk_window_set_default_size (GTK_WINDOW (src_dialog), 640, 360);
	gnome_apt_setup_dialog (src_dialog);
	g_signal_connect (G_OBJECT (src_dialog), "response", G_CALLBACK (response_cb), this);

  GtkWidget* frame = gtk_frame_new(NULL);
	gtk_container_set_border_width (GTK_CONTAINER (frame), GAPT_PAD);
	GtkWidget* vbox  = gtk_vbox_new (FALSE, GAPT_PAD);
	gtk_container_set_border_width (GTK_CONTAINER (vbox), GAPT_PAD);

	gchar* titles[N_COLS] = {
		_("Enabled"),
		_("Type"),
		_("Uniform Resource Identifier"),
		_("Distribution"),
		_("Section"),
		"Record"	/* Should never be used */
	};

	GtkListStore* store = gtk_list_store_new (N_COLS,
	      G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
	      G_TYPE_STRING, G_TYPE_POINTER);

	list<SourcesList::SourceRecord*>::iterator it =  src_list->SourceRecords.begin();
	while (it != src_list->SourceRecords.end()) {
		if ((*it)->Type & SourcesList::Comment) {
			++it;
			continue;
		}

		string Sections;
		for (unsigned int J = 0; J < (*it)->NumSections; ++J) {
			Sections += (*it)->Sections[J];
			Sections += " ";
		}

		GtkTreeIter iter;

		gtk_list_store_append (store, &iter);
		gtk_list_store_set (store, &iter,
			C_STATUS, !((*it)->Type & SourcesList::Disabled),
			C_TYPE, (*it)->GetType().c_str(),
			C_URI, (*it)->URI.c_str(),
			C_DIST, (*it)->Dist.c_str(),
			C_SECT, Sections.c_str(),
			C_RECORD, (gpointer) (*it),
			-1);
		++it;
	}

	GtkWidget* tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (store));

	for (int a = C_TYPE; a <= C_SECT; a++) {
		GtkCellRenderer* renderer = gtk_cell_renderer_text_new ();
		GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes (
			titles[a], renderer, "text", a, NULL);
		gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);
	}

	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree));
	gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);

	/*g_signal_connect (G_OBJECT (selection), "changed", G_CALLBACK (sel_changed_cb), this);*/
	g_signal_connect (G_OBJECT (tree), "row-activated", G_CALLBACK (row_activated_cb), this);

  GtkWidget* sw = gtk_scrolled_window_new(NULL,NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
                                 GTK_POLICY_AUTOMATIC,
                                 GTK_POLICY_AUTOMATIC);
	gtk_container_add (GTK_CONTAINER (sw), tree);

  gtk_box_pack_start(GTK_BOX(vbox),
                     sw,
                     TRUE, TRUE, 0);

  GtkWidget* hbox = gtk_hbox_new(0,FALSE);

  gtk_box_pack_start(GTK_BOX(vbox),
                     hbox,
					 FALSE,FALSE,0);

	b_add_ = gtk_button_new_from_stock (GTK_STOCK_ADD);
	gtk_button_set_label (GTK_BUTTON (b_add_), _("Add source"));
  gtk_box_pack_start(GTK_BOX(hbox),
                     b_add_,
					 TRUE,TRUE,0);

	b_del_ = gtk_button_new_from_stock (GTK_STOCK_REMOVE);
	gtk_button_set_label (GTK_BUTTON (b_del_), _("Remove source"));
  gtk_box_pack_start(GTK_BOX(hbox),
                     b_del_,
					 TRUE,TRUE,0);

	b_edit_ = gtk_button_new_from_stock (GTK_STOCK_PROPERTIES);
	gtk_button_set_label (GTK_BUTTON (b_edit_), _("Edit source"));
  gtk_box_pack_start(GTK_BOX(hbox),
                     b_edit_,
					 TRUE,TRUE,0);

	g_signal_connect (G_OBJECT (b_add_), "clicked", G_CALLBACK (add_wizard_cb), src_dialog);
	g_signal_connect (G_OBJECT (b_del_), "clicked", G_CALLBACK (delete_source_cb), this);
	g_signal_connect (G_OBJECT (b_edit_), "clicked", G_CALLBACK (edit_source_cb), this);

	gtk_box_pack_start (GTK_BOX (GTK_DIALOG (src_dialog)->vbox), vbox, TRUE, TRUE, 0);
	gtk_widget_show_all (src_dialog);
}

/*
 * Add a source to the list (usually called by the wizard).
 * Error means that the source was NOT ADDED.
 *
 */
Sources::SourceAddResult
Sources::add_source (string dist, string uri, string* sections, gint count) {
  SourceAddResult error = Ok;

  // FIXME - Check the data and set error accordingly

  if (error == Ok)
    {
		SourcesList::SourceRecord *rec = src_list->AddSource (
		      SourcesList::Deb, "", uri, dist, sections, count,
		      _config->FindFile ("Dir::Etc::sourcelist"));

		string Sections;
		for (unsigned int J = 0; J < rec->NumSections; ++J) {
			Sections += rec->Sections[J];
			Sections += " ";
		}

		GtkTreeModel* model = NULL;

		GtkTreeView* tree = gtk_tree_selection_get_tree_view (selection);
		model = gtk_tree_view_get_model (tree);
		if (model) {
			GtkTreeIter iter;

			gtk_list_store_append (GTK_LIST_STORE (model), &iter);
			gtk_list_store_set (GTK_LIST_STORE (model), &iter,
			      C_STATUS, TRUE, C_TYPE, "deb", C_URI, uri.c_str(),
			      C_DIST, dist.c_str(), C_SECT, Sections.c_str(), C_RECORD, rec,
			      -1);
		} else {
/* FIXME - This shouldn't happen */
		}
    }
  
  return error;
}

void 
Sources::apply (GtkWidget* wdg) {
	if (!src_list->UpdateSources()) {
/* FIXME: should use strerror_r() but glibc is seriously broken */
		GtkWidget* dialog = gtk_message_dialog_new (
			GTK_WINDOW (wdg), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
			"Following error occurred when trying to write the repository list:\n\n%s",
			strerror (errno));
		gnome_apt_setup_dialog (dialog);
		gtk_dialog_run (GTK_DIALOG (dialog));

		gtk_widget_destroy (dialog);
	}
}

gint
Sources::close (GtkWidget* wdg) {
  gnome_apt_sources_wizard_shutdown();

	gtk_widget_destroy (wdg);

	if (src_list) {
		delete src_list;
		src_list = 0;
	}

  return FALSE;
}

void
Sources::add_wizard_cb (GtkWidget* w, gpointer data)
{
	GtkWidget* win = static_cast<GtkWidget*> (data);
	gnome_apt_sources_wizard()->add (win);
}

void
Sources::delete_source_cb (GtkWidget* w, gpointer data)
{
  Sources* p = static_cast<Sources*>(data);

  p->delete_source();
}

void
Sources::delete_source()
{
	GtkTreeIter iter;
	GtkTreeModel* model;

	if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
		gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
	}
}

void
Sources::edit_source_cb(GtkWidget* w, gpointer data)
{
  Sources* p = static_cast<Sources*>(data);

	GtkWidget* win = gtk_widget_get_toplevel (w);
	if (!GTK_WIDGET_TOPLEVEL (win)) {
		win = NULL;
	}
	p->edit_source (win);
}

void
Sources::edit_source (GtkWidget* parent) {
	GtkTreeIter iter;
	GtkTreeModel* model;

	if (!gtk_tree_selection_get_selected (selection, &model, &iter)) {
		return;
	}

	GtkWidget* edit_dialog = gtk_dialog_new_with_buttons (
		_("Edit source"), GTK_WINDOW (parent), GTK_DIALOG_DESTROY_WITH_PARENT,
		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
		GTK_STOCK_OK, GTK_RESPONSE_OK, NULL);
	gtk_window_set_default_size (GTK_WINDOW (edit_dialog), 480, -1);

	GtkWidget* vbox = gtk_vbox_new (FALSE, GAPT_PAD);
	gtk_container_set_border_width (GTK_CONTAINER (vbox), GAPT_PAD);
	gtk_box_pack_start (GTK_BOX (GTK_DIALOG (edit_dialog)->vbox), vbox, TRUE, TRUE, 0);

	GtkWidget* label = gtk_label_new (_("<b>Edit Repository Definition</b>"));
	gtk_label_set_use_markup (GTK_LABEL (label), TRUE);
	gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
	gtk_box_pack_start (GTK_BOX (vbox), label, TRUE, TRUE, 0);
  
	GtkWidget* hbox = gtk_hbox_new (FALSE, GAPT_PAD);
	gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 0);

	label = gtk_label_new ("");
	gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, GAPT_PAD);

  GtkWidget* vbox_labels = gtk_vbox_new(TRUE, 0);

	GtkWidget* label_uri = gtk_label_new (_("URI:"));
  gtk_misc_set_alignment(GTK_MISC(label_uri), 0.0, 0.5);
	gtk_box_pack_start (GTK_BOX (vbox_labels), label_uri, TRUE, TRUE, GAPT_PAD);

	GtkWidget* label_dist = gtk_label_new (_("Distribution:"));
	gtk_misc_set_alignment (GTK_MISC (label_dist), 0.0, 0.5);
	gtk_box_pack_start (GTK_BOX (vbox_labels), label_dist, TRUE, TRUE, GAPT_PAD);

	GtkWidget* label_section = gtk_label_new (_("Section:"));
  gtk_misc_set_alignment(GTK_MISC(label_section), 0.0, 0.5);
	gtk_box_pack_start (GTK_BOX (vbox_labels), label_section, TRUE, TRUE, GAPT_PAD);

	gtk_box_pack_start (GTK_BOX (hbox), vbox_labels, FALSE, FALSE, GAPT_PAD);

  GtkWidget* vbox_edit = gtk_vbox_new(TRUE, 0);

  gchar* ptr_dist;
  gchar* ptr_uri;
  gchar* ptr_section;

	gtk_tree_model_get (model, &iter,
		C_DIST, &ptr_dist, C_URI, &ptr_uri, C_SECT, &ptr_section, -1);

  edit_dialog_uri_ = gtk_entry_new();

  gtk_entry_set_text(GTK_ENTRY(edit_dialog_uri_),
                     ptr_uri);
	gtk_editable_set_position (GTK_EDITABLE (edit_dialog_uri_), -1);
	gtk_box_pack_start (GTK_BOX (vbox_edit), edit_dialog_uri_, TRUE, FALSE, GAPT_PAD);

	edit_dialog_dist_ = gtk_entry_new();
	gtk_entry_set_text (GTK_ENTRY (edit_dialog_dist_), ptr_dist);
	gtk_editable_set_position (GTK_EDITABLE (edit_dialog_dist_), -1);
	gtk_box_pack_start (GTK_BOX (vbox_edit), edit_dialog_dist_, TRUE, FALSE, GAPT_PAD);

  edit_dialog_section_ = gtk_entry_new();

  gtk_entry_set_text(GTK_ENTRY(edit_dialog_section_),
                     ptr_section);

	gtk_editable_set_position (GTK_EDITABLE (edit_dialog_section_), -1);
	gtk_box_pack_start (GTK_BOX (vbox_edit), edit_dialog_section_, TRUE, FALSE, GAPT_PAD);

	g_free (ptr_dist);
	g_free (ptr_uri);
	g_free (ptr_section);

	gtk_box_pack_start (GTK_BOX (hbox), vbox_edit, TRUE, TRUE, GAPT_PAD);

	gtk_widget_show_all (edit_dialog);
	g_signal_connect (G_OBJECT (edit_dialog), "response", G_CALLBACK (edit_source_click_cb), this);

	gtk_widget_set_sensitive (parent, FALSE);
}

void
Sources::edit_source_close (GtkWidget* wdg) {
	GtkWidget* parent = GTK_WIDGET (gtk_window_get_transient_for (GTK_WINDOW (wdg)));
	if (GTK_IS_WIDGET (wdg)) {
		gtk_widget_destroy (wdg);
	}

	gtk_widget_set_sensitive (parent, TRUE);
}

void
Sources::edit_source_click_cb (GtkWidget* wdg, gint response, gpointer data) {
  Sources* ptr = static_cast<Sources*>(data);

	if (response == GTK_RESPONSE_OK) {
      ptr->edit_source_ok();
	} else if (response != GTK_RESPONSE_CANCEL && response != GTK_RESPONSE_DELETE_EVENT) {
		g_warning ("Got response: %d", response);
	}

	ptr->edit_source_close (wdg);
}

void
Sources::edit_source_ok()
{
	GtkTreeIter iter;
	GtkTreeModel* model;

	if (gtk_tree_selection_get_selected (selection, &model, &iter)) {
		SourcesList::SourceRecord* rec;
		gtk_tree_model_get (model, &iter, C_RECORD, &rec, -1);

		rec->URI = gtk_entry_get_text (GTK_ENTRY (edit_dialog_uri_));
		rec->Dist = gtk_entry_get_text (GTK_ENTRY (edit_dialog_dist_));

		/* It's sufficient to read all sections into one string; it may not
		 * be principally correct but in practice it doesn't matter at all
		 */
		delete [] rec->Sections;
		rec->NumSections = 1;
		rec->Sections = new string[1];
		rec->Sections[0] = gtk_entry_get_text (GTK_ENTRY (edit_dialog_section_));

  // FIXME - check the validity of input
		gtk_list_store_set (GTK_LIST_STORE (model), &iter,
			C_DIST, rec->Dist.c_str(), C_URI, rec->URI.c_str(),
			C_SECT, rec->Sections[0].c_str(), -1);
	}
}

static Sources* sources = 0;

Sources*
gnome_apt_sources()
{
  if (sources == 0)
    sources = new Sources;

  return sources;
}

void     
gnome_apt_sources_shutdown()
{
  gnome_apt_sources_wizard_shutdown();

  if (sources != 0)
    delete sources;

  sources = 0;
}
