/*
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 * 
 * The Original Code is mozilla.org code.
 * 
 * The Initial Developer of the Original Code is Christopher Blizzard.
 * Portions created by Christopher Blizzard are Copyright (C)
 * Christopher Blizzard.  All Rights Reserved.
 * 
 * Contributor(s):
 *   Christopher Blizzard <blizzard@mozilla.org>
 */

#include "EmbedProgress.h"

#include <nsIChannel.h>
#define MOZILLA_STRICT_API
#include <nsEmbedString.h>
#undef MOZILLA_STRICT_API

#include <nsIWebProgress.h>
#include <nsIURI.h>
#include <nsCRT.h>
#include <nsIDOMWindow.h>
 
EmbedProgress::EmbedProgress(void)
{
  mOwner = nsnull;
}

EmbedProgress::~EmbedProgress()
{
}

NS_IMPL_ISUPPORTS2(EmbedProgress,
		   nsIWebProgressListener,
		   nsISupportsWeakReference)

nsresult
EmbedProgress::Init(EmbedPrivate *aOwner)
{
  mOwner = aOwner;
  return NS_OK;
}

NS_IMETHODIMP
EmbedProgress::OnStateChange(nsIWebProgress *aWebProgress,
			     nsIRequest     *aRequest,
			     PRUint32        aStateFlags,
			     nsresult        aStatus)
{
  // give the widget a chance to attach any listeners
  mOwner->ContentStateChange();
  // if we've got the start flag, emit the signal
  if ((aStateFlags & GTK_MOZ_EMBED_FLAG_IS_NETWORK) && 
      (aStateFlags & GTK_MOZ_EMBED_FLAG_START))
  {
    g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		  moz_embed_signals[NET_START], 0);
  }

  // get the uri for this request
  char *uriString = NULL;
  RequestToURIString(aRequest, &uriString);

  if (uriString)
  {
    nsEmbedCString tmpString;
    NS_UTF16ToCString(mOwner->mURI,
		      NS_CSTRING_ENCODING_UTF8, tmpString); 

    // is it the same as the current URI?
    if (tmpString.get() && !strcmp(tmpString.get(), uriString))
    {
      // for people who know what they are doing
      g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		    moz_embed_signals[NET_STATE], 0, 
		    aStateFlags, aStatus);
    }
    g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		  moz_embed_signals[NET_STATE_ALL], 0,
		  (gpointer)(const char *)uriString,
		  (gint)aStateFlags, (gint)aStatus);
    g_free(uriString);
  }
  // and for stop, too
  if ((aStateFlags & GTK_MOZ_EMBED_FLAG_IS_NETWORK) && 
      (aStateFlags & GTK_MOZ_EMBED_FLAG_STOP))
  {
    g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		  moz_embed_signals[NET_STOP], 0);
    // let our owner know that the load finished
    mOwner->ContentFinishedLoading();
  }

  return NS_OK;
}

NS_IMETHODIMP
EmbedProgress::OnProgressChange(nsIWebProgress *aWebProgress,
				nsIRequest     *aRequest,
				PRInt32         aCurSelfProgress,
				PRInt32         aMaxSelfProgress,
				PRInt32         aCurTotalProgress,
				PRInt32         aMaxTotalProgress)
{

  char *uriString;
  RequestToURIString(aRequest, &uriString);
  
  nsEmbedCString tmpString;
  NS_UTF16ToCString(mOwner->mURI,
		    NS_CSTRING_ENCODING_UTF8, tmpString); 

  // is it the same as the current uri?
  if (uriString && !strcmp(tmpString.get(), uriString))
  {
    g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		  moz_embed_signals[PROGRESS], 0,
		  aCurTotalProgress, aMaxTotalProgress);
  }

  g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		moz_embed_signals[PROGRESS_ALL], 0,
		(const char *)uriString,
		aCurTotalProgress, aMaxTotalProgress);
  if (uriString)
    g_free(uriString);
  return NS_OK;
}

NS_IMETHODIMP
EmbedProgress::OnLocationChange(nsIWebProgress *aWebProgress,
				nsIRequest     *aRequest,
				nsIURI         *aLocation)
{
  nsEmbedCString newURI;
  NS_ENSURE_ARG_POINTER(aLocation);
  aLocation->GetSpec(newURI);

  // Make sure that this is the primary frame change and not
  // just a subframe.
  PRBool isSubFrameLoad = PR_FALSE;
  if (aWebProgress) {
    nsCOMPtr<nsIDOMWindow> domWindow;
    nsCOMPtr<nsIDOMWindow> topDomWindow;

    aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));

    // get the root dom window
    if (domWindow)
      domWindow->GetTop(getter_AddRefs(topDomWindow));

    if (domWindow != topDomWindow)
      isSubFrameLoad = PR_TRUE;
  }

  if (!isSubFrameLoad) {
    mOwner->SetURI(newURI.get());
    g_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
		  moz_embed_signals[LOCATION], 0);
  }

  return NS_OK;
}

NS_IMETHODIMP
EmbedProgress::OnStatusChange(nsIWebProgress  *aWebProgress,
			      nsIRequest      *aRequest,
			      nsresult         aStatus,
			      const PRUnichar *aMessage)
{
  // need to make a copy so we can safely cast to a void *
  PRUnichar *tmpString = nsCRT::strdup(aMessage);

  g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		moz_embed_signals[STATUS_CHANGE], 0,
		NS_STATIC_CAST(void *, aRequest),
		NS_STATIC_CAST(int, aStatus),
		NS_STATIC_CAST(void *, tmpString));

  nsMemory::Free(tmpString);

  return NS_OK;
}

NS_IMETHODIMP
EmbedProgress::OnSecurityChange(nsIWebProgress *aWebProgress,
				nsIRequest     *aRequest,
				PRUint32         aState)
{
  g_signal_emit(G_OBJECT(mOwner->mOwningWidget),
		moz_embed_signals[SECURITY_CHANGE], 0,
		NS_STATIC_CAST(void *, aRequest),
		aState);
  return NS_OK;
}

/* static */
void
EmbedProgress::RequestToURIString(nsIRequest *aRequest, char **aString)
{
  // is it a channel
  nsCOMPtr<nsIChannel> channel;
  channel = do_QueryInterface(aRequest);
  if (!channel)
    return;
  
  nsCOMPtr<nsIURI> uri;
  channel->GetURI(getter_AddRefs(uri));
  if (!uri)
    return;
  
  nsEmbedCString uriString;
  uri->GetSpec(uriString);

  *aString = strdup(uriString.get());
}
