/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: setup.cpp,v 1.11.6.7 2004/10/27 16:59:17 nhart Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

/* This function implements hmw_preferences. It contains a number of
   unprefixed supporting functions.
 */
 
#include "hxcom.h"
#include "hxwintyp.h"
#include "hxcore.h"
 
#include <gtk/gtk.h>

#include "hlxclib/stdlib.h"
#include "hlxclib/stdio.h"
#include "hlxclib/string.h"
#include "hlxclib/sys/types.h"
#include "hlxclib/sys/stat.h"
#include <unistd.h>

 
#include "hxplayer.h"
#include "hxgprefs.h"
#include "hxgvalue.h"
#include "commonapp.h"
#include "mainapp.h"
#include "mimetypes.h"
#include "switchboard.h"
#include "mailcap.h"
 
#include "hxplayer-i18n.h"

/* for mime setup */
#include "HXClientCOMAccess.h"
#include "chxmimemanager.h"
#include "ihxmimeassocmanager.h"

extern "C"
{
#include "setup_callbacks.h"
#include "support.h"

    gboolean check_has_mime_support();
};


gboolean check_has_mime_support()
{
    gboolean bHasMimeSupport = FALSE;

    IUnknown* pUnk = NULL;
    if (ClientEngineGetUnknown((void**)&pUnk))
    {
	CHXMimeManager mimemgr;
	if (SUCCEEDED(mimemgr.Init(pUnk)))
	{
	    const char* pName = NULL;
	    IHXMimeAssocManager* pMimeMgr = NULL;
	    mimemgr.GetFirstMimeAssocManager(pName, pMimeMgr);
	    if (pMimeMgr)
	    {
		bHasMimeSupport = TRUE;
		HX_RELEASE(pMimeMgr);
	    }
	}
    }
    return bHasMimeSupport;
}

void claim_mimes(CHXMimeManager* pMimeMgr, 
		 const char** ppMimes, 
		 const char* pAppId,
		 BOOL bOverride)
{
    while (*ppMimes)
    {
	pMimeMgr->SetAssoc(*ppMimes, pAppId, bOverride);
	++ppMimes;
    }
}

void populate_textview(GtkWidget* widget, const char* path)
{
    gchar* text = NULL;
    gsize size = 0;
    GError* err = NULL;
    gchar* fullpath = NULL;
    const gchar* lang = NULL;

    lang = hxcommon_get_gettext_language();
    if (lang)
    {
	gchar* pos = NULL;
	gchar* langpath = NULL;

	// strip encoding
	if ((pos = (gchar*)strchr(lang, '.')))
	{
	    *pos = '\0';
	}

	langpath = g_strdup_printf("share/locale/%s/%s", lang, path);
	fullpath = hxcommon_get_rel_app_path(langpath);
	g_free(langpath);

	if (fullpath)
	{
	    if (!g_file_test(fullpath, G_FILE_TEST_EXISTS))
	    {
		// strip country code
		if ((pos = (gchar*)strchr(lang, '_')))
		{
		    *pos = '\0';
		}

		g_free(fullpath);
		langpath = g_strdup_printf("share/locale/%s/%s", lang, path);
		fullpath = hxcommon_get_rel_app_path(langpath);
		g_free(langpath);

		if (fullpath)
		{
		    if (!g_file_test(fullpath, G_FILE_TEST_EXISTS))
		    {
			// no localized text file found
			g_free(fullpath);
			fullpath = hxcommon_get_rel_app_path(path);
		    }
		}
	    }
	}
    }
    else
    {
	fullpath = hxcommon_get_rel_app_path(path);
    }

    if (fullpath)
    {
	if (g_file_get_contents(fullpath, &text, &size, &err))
	{
	    GtkTextBuffer* buffer;
	    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(widget));
	    gtk_text_buffer_set_text(buffer, text, size);
	    g_free(text);
	}
	g_free(fullpath);
    }
}


gboolean
hsad_setup_assistant_delete_event        (GtkWidget       *widget,
					  GdkEvent        *event,
					  gpointer         user_data)
{

  return FALSE;
}


gboolean
hsad_setup_assistant_configure_event     (GtkWidget       *widget,
					  GdkEventConfigure *event,
					  gpointer         user_data)
{
    populate_textview(lookup_widget(widget, "notes_textview"), "README");

#ifdef HELIX_FEATURE_REAL_BRANDING // XXXNH: no EULA for helix player
    populate_textview(lookup_widget(widget, "eula_textview"), "LICENSE");
#endif

    return FALSE;
}


void
hsad_setup_notebook_switch_page          (GtkNotebook     *notebook,
					  GtkNotebookPage *page,
					  guint            page_num,
					  gpointer         user_data)
{

}


void
hsad_quit_clicked                        (GtkButton       *button,
					  gpointer         user_data)
{
    gint page;
    gint num_pages;

    GtkWidget* pWindow = gtk_widget_get_toplevel(GTK_WIDGET(user_data));
    GtkWidget* pNotebook = lookup_widget(pWindow, "setup_notebook");

    gtk_widget_hide(gtk_widget_get_toplevel(GTK_WIDGET(user_data)));

    page = gtk_notebook_get_current_page(GTK_NOTEBOOK(pNotebook));

    // GTK2.2
    // num_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(sa->notebook));
    num_pages = g_list_length(GTK_NOTEBOOK(pNotebook)->children);
        
    if(page == (num_pages - 1))
    {
        GtkWidget* check_for_updates_checkbox = lookup_widget(pWindow, "check_for_updates_checkbox");
        GtkWidget* configure_mozilla_helpers_checkbox = lookup_widget(pWindow, "configure_mozilla_helpers_checkbox");

        if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check_for_updates_checkbox)))
        {
            gchar* url = hx_switchboard_get_upgrade_url(NULL);
            hxcommon_url_show(url);
            g_free(url);    
        }

        if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(configure_mozilla_helpers_checkbox)))
        {
            mailcap_update();
        }
    }
}


void
hsad_forward_clicked                     (GtkButton       *button,
					  gpointer         user_data)
{
#ifndef HELIX_FEATURE_REAL_BRANDING
    // if this is the release notes pane in the helix player and we have no
    // mime support, then close the dialog
    GtkWidget* pWindow = gtk_widget_get_toplevel(GTK_WIDGET(user_data));

    GtkWidget* pNotebook = lookup_widget(pWindow, "setup_notebook");

    // this is the last pane
    if (!g_object_get_data(G_OBJECT(pWindow), "mime-supported") &&
	gtk_notebook_get_current_page(GTK_NOTEBOOK(pNotebook)) == 1)
    {
	g_object_set_data(G_OBJECT(pWindow), "eula-accepted", (void*)1);
	gtk_widget_hide(pWindow);
	return;
    }
#endif

    GtkWidget* notebook = lookup_widget(GTK_WIDGET(user_data),
                                        "setup_notebook");
    gtk_notebook_next_page(GTK_NOTEBOOK(notebook));
}


void
hsad_print_clicked                       (GtkButton       *button,
					  gpointer         user_data)
{

}


void
hsad_back_clicked                        (GtkButton       *button,
					  gpointer         user_data)
{
    GtkWidget* notebook = lookup_widget(GTK_WIDGET(user_data),
                                        "setup_notebook");
    gtk_notebook_prev_page(GTK_NOTEBOOK(notebook));

}


void
hsad_privacy_clicked                     (GtkButton       *button,
					  gpointer         user_data)
{
    gchar* url = hx_switchboard_get_privacy_url();
    hxcommon_url_show(url);
    g_free(url);
}


void
hsad_accept_clicked                      (GtkButton       *button,
					  gpointer         user_data)
{
    GtkWidget* pWindow = gtk_widget_get_toplevel(GTK_WIDGET(user_data));

	GtkWidget* notebook = lookup_widget(GTK_WIDGET(user_data),
                                        "setup_notebook");

    if (!g_object_get_data(G_OBJECT(pWindow), "mime-supported"))
    {
        gtk_notebook_next_page(GTK_NOTEBOOK(notebook));
    }

    gtk_notebook_next_page(GTK_NOTEBOOK(notebook));
    
    g_object_set_data(G_OBJECT(pWindow), "eula-accepted", (void*)1);
}


void
hsad_done_clicked                        (GtkButton       *button,
					  gpointer         user_data)
{
    GtkWidget* pWindow = gtk_widget_get_toplevel(GTK_WIDGET(user_data));
    gtk_widget_hide(pWindow);

    IUnknown* pUnk = NULL;
    if (ClientEngineGetUnknown((void**)&pUnk))
    {
	CHXMimeManager mimemgr;
	if (SUCCEEDED(mimemgr.Init(pUnk)))
	{
	    const char* pAppId = APP_NAME_SHORT;
	    gchar* pIcon = hxcommon_locate_file("icon.png");
	    gchar* pAppCmd = hxcommon_get_rel_app_path(APP_NAME_SHORT);
	    const BOOL bCanOpenMultiple = TRUE;
	    const BOOL bTerminal = FALSE;
	    mimemgr.SetupApp(pAppId, APP_NAME_LONG, pAppCmd, 
			     bCanOpenMultiple, bTerminal);
	    g_free(pAppCmd);

	    mimemgr.SetupProtocol("application/rtsp",
				  "rtsp",
				  "real time streaming protocol",
				  pIcon);
	    mimemgr.SetupAllFileFormats(pIcon, FALSE);
	    g_free(pIcon);

	    GtkWidget* pButton;
	    BOOL bForceClaim = TRUE;

// XXXNH: we give the option of not claiming these in the helix player
#ifndef HELIX_FEATURE_REAL_BRANDING
	    bForceClaim = FALSE; // we want to claim any unclaimed ones
	    pButton = lookup_widget(pWindow, "rn_checkbox");
	    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pButton)))
	    {
		// we've been asked to claim them all
		bForceClaim = TRUE;
	    }
#endif
	    {
		const char* kRNMimes[] = 
		{
		    "application/vnd.rn-realmedia-secure",
		    "application/vnd.rn-realmedia-vbr",
		    "application/x-musicnet-download",
		    "application/x-musicnet-stream",
		    "application/x-pn-quicktime-stream",
		    "application/x-pn-realmedia",
		    "audio/x-musicnet-stream",
		    "audio/x-pn-realaudio",
		    "audio/x-pn-realaudio-encrypted",
		    "video/x-pn-realvideo-encrypted",
		    "video/x-real-video", // XXXNH: not real types, but we
		    "audio/x-real-audio", // want to grab these if they exist
		    NULL
		};

		claim_mimes(&mimemgr, kRNMimes, pAppId, bForceClaim);
	    }
	    
	    pButton = lookup_widget(pWindow, "rtsp_checkbox");
	    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pButton)))
	    {
		const char* kRTSPMimes[] = 
		{
		    NULL
		};

		claim_mimes(&mimemgr, kRTSPMimes, pAppId, TRUE);
	    }
	    
	    pButton = lookup_widget(pWindow, "sdp_checkbox");
	    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pButton)))
	    {
		const char* kSDPMimes[] = 
		{
		    NULL
		};

		claim_mimes(&mimemgr, kSDPMimes, pAppId, TRUE);
	    }
	    
	    pButton = lookup_widget(pWindow, "smil_checkbox");
	    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pButton)))
	    {
		const char* kSMILMimes[] = 
		{
		    "text/vnd.rn-realtext",
		    "application/x-pn-realtext",
		    "application/vnd.rn-realtext",
		    "image/vnd.rn-realpix",
		    "application/vnd.rn-realpix",
		    "application/smil",
		    NULL
		};

		claim_mimes(&mimemgr, kSMILMimes, pAppId, TRUE);
	    }
	    mimemgr.Commit();
	}
	HX_RELEASE(pUnk);
    }
}
