/*
 * Copyright (C) 2007  Miriam Ruiz <little_miry@yahoo.es>
 *
 * 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
 */

#include "aux.h"
#include "common.h"

#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <string>

#include <FL/Fl.H>
#include <FL/Fl_Help_View.H>

bool HTMLView::ExternalBrowser(const char *uri)
{
	pid_t pid = -1;
	if ((pid=fork()) == -1)
	{
		ERROR_PRINTF("fork: %s\n", strerror(errno));
		return false;
	}

	if (strchr(uri, '"')) return false; /* No "s allowed in the uri for the moment */

	if (pid) /* A positive (non-negative) PID indicates the parent process */
		return true;

	/* A zero PID indicates that this is the child process */
	std::string command = std::string("/usr/bin/x-www-browser \"") + uri +"\"";
	if (execl("/bin/sh", "sh", "-c", command.c_str(), (char *) 0) == -1)
		ERROR_PRINTF("exec: %s\n", strerror(errno));

	exit(1); /* This point should never be reached */
}

HTMLView::HTMLView(int xx, int yy, int ww, int hh, const char *l) : Fl_Help_View(xx, yy, ww, hh, l), draw_cb(NULL)
{
	link(HTMLView::link_cb);
}

HTMLView::~HTMLView()
{
}

const char *HTMLView::link_cb(Fl_Widget *w, const char *uri)
{
	HTMLView *html_view = (HTMLView *)w;
	printf("PackageView::link_cb(): Widget=0x%lX, URI=\"%s\"\n", (unsigned long)w, uri);

	if (html_view->draw_cb) html_view->draw_cb(html_view);

	if (!strncasecmp("http:", uri, 5) || !strncasecmp("ftp:", uri, 4) || !strncasecmp("https:", uri, 6))
	{
		HTMLView::ExternalBrowser(uri);
		return NULL;
	}

	if (!strncasecmp("mailto:", uri, 7))
	{
		return NULL;
	}

		if (!strncasecmp("pkg:", uri, 4))
	{
		return NULL;
	}

	return uri;
}
