/*
 *  Copyright (C) 2001 Philip Langdale
 *
 *  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, 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 "nsString.h"
#include "nsIMailtoUrl.h"
#include "nsNetUtil.h"
#include "nsIExternalProtocolService.h"
#include "nsCExternalHandlerService.h"
#include "nsCRT.h"

#include "gUrlCID.h"

#include "MailtoProtocolHandler.h"

static NS_DEFINE_CID(kMailtoURLCID, NS_MAILTOURL_CID);

/* Implementation file */
NS_IMPL_ISUPPORTS2 (GMailtoProtocolHandler, nsIProtocolHandler, nsIContentHandler)

/* nsIURI newURI (in string aSpec, in nsIURI aBaseURI); */
NS_IMETHODIMP GMailtoProtocolHandler::NewURI(const nsACString &aSpec,
					     const char *aOriginCharset,
					     nsIURI *aBaseURI,
					     nsIURI **_retval)
{
	nsresult rv = NS_OK;
	nsCOMPtr <nsIURI> newUri;

	rv = nsComponentManager::CreateInstance(kMailtoURLCID, nsnull,
						NS_GET_IID(nsIURI),
						getter_AddRefs(newUri));

        if (NS_SUCCEEDED(rv)) 
        {
		newUri->SetSpec(aSpec);
		rv = newUri->QueryInterface(NS_GET_IID(nsIURI),
					    (void **) _retval);
        }
	return rv;

}

NS_IMETHODIMP GMailtoProtocolHandler::HandleContent (
					const char * aContentType,
					const char * aCommand,
					nsISupports * aWindowContext,
					nsIRequest *aRequest)
{
	nsresult rv = NS_OK;
	if (!aRequest)
		return NS_ERROR_NULL_POINTER;
  	// First of all, get the content type and make sure it is a 
  	// content type we know how to handle!
	if (nsCRT::strcasecmp(aContentType, mMimeType.get()) == 0)
	{
		nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
		if(!channel) return NS_ERROR_FAILURE;

		nsCOMPtr<nsIURI> uri;
		rv = channel->GetURI(getter_AddRefs(uri));
		if (NS_FAILED(rv)) return rv;

		nsCOMPtr<nsIMailtoUrl> mailtoUrl =
				do_QueryInterface (uri, &rv);
		if (NS_FAILED(rv)) return rv;

		aRequest->Cancel(NS_BINDING_ABORTED);
		if (uri)
		{
			nsCOMPtr<nsIExternalProtocolService> ps = 
				do_GetService (NS_EXTERNALPROTOCOLSERVICE_CONTRACTID, &rv);
			if (NS_FAILED(rv) || !ps) return NS_ERROR_FAILURE;
			ps->LoadUrl (uri);
		}
	}
	return rv;
}
