/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: signin.cpp,v 1.2.2.4 2004/07/12 20:41:41 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 ***** */

/* Helix includes */
#include "hxcom.h"
#include "hxwintyp.h"
#include "hxcore.h"
#include "ihxpckts.h"
#include "ihxident.h"
#include "hxtypes.h"
#include "hxresult.h"
#include "hxbuffer.h"
#include "hxstrutl.h"

/* GtkHX includes */
#include "hxgprefs.h"

#include "appver.h"

#include "cr1serviceauth.h"
#include "ir1clientpreferences.h"

#include "signin.h"
#include "hxplayer.h"
#include "commonapp.h"

class CR1ClientPreferences;
class CR1CommonClassFactory;

static CR1ServiceAuthentication* g_pR1ServiceAuthentication = NULL;
static CR1ClientPreferences*     g_pR1ClientPreferences     = NULL;
static CR1CommonClassFactory*    g_pR1CommonClassFactory    = NULL;

/* CR1ClientPreferences
 * ====================
 * Required for sign in
 */

class CR1ClientPreferences : public CUnknownIMP,
                             public IR1ClientPreferences
{
public:
    CR1ClientPreferences();
    virtual ~CR1ClientPreferences();

    DECLARE_UNKNOWN( CR1ClientPreferences )

    
    /*
     *  IR1ClientPreferences methods
     */
    STDMETHOD ( GetClientPreference ) ( THIS_
                                        const char* pKey,
                                        IHXBuffer**outBuffer );
    STDMETHOD ( SetClientPreference ) ( THIS_
                                        const char* pKey,
                                        IHXBuffer* buffer );
    STDMETHOD ( SetClientPreferenceString ) ( THIS_
                                              const char* pKey,
                                              const char* pString );


    void Init(HXMainWindow* pWindow,
              IHXCommonClassFactory* pCCF);
    
private:
    HXMainWindow* m_pWindow;
    IHXCommonClassFactory* m_pCCF;
};

BEGIN_INTERFACE_LIST( CR1ClientPreferences )
INTERFACE_LIST_ENTRY_SIMPLE( IR1ClientPreferences );
END_INTERFACE_LIST


CR1ClientPreferences::CR1ClientPreferences()
{
    m_pWindow = NULL;
    m_pCCF = NULL;
}


CR1ClientPreferences::~CR1ClientPreferences()
{
    m_pWindow = NULL;
    if(m_pCCF)
    {
        HX_RELEASE(m_pCCF);
        m_pCCF = NULL;
    }
}

void
CR1ClientPreferences::Init(HXMainWindow* window, IHXCommonClassFactory* pCCF)
{
    m_pWindow = window;
    m_pCCF = pCCF;
    HX_ADDREF(m_pCCF);
}

STDMETHODIMP CR1ClientPreferences::GetClientPreference( const char* pKey,
                                                        IHXBuffer** outBuffer )
{
    HX_RESULT retVal = HXR_FAIL;
    const gchar* strValue;
    *outBuffer = NULL;

    strValue = hxwindow_get_sign_in_property(m_pWindow, pKey);
    if(strValue)
    {
        retVal = m_pCCF->CreateInstance(CLSID_IHXBuffer,
                                      (void**) outBuffer);

        if(SUCCEEDED(retVal))
        {
            (*outBuffer)->Set((const UCHAR*)strValue, strlen(strValue) + 1);
            retVal = HXR_OK;
        }
    }

    if(FAILED(retVal))
    {
        /* Fall back to non-signin preferences */
        HXEntry *pPrefEntry;
        pPrefEntry = hx_prefs_get_entry(pKey);
        if(pPrefEntry)
        {
            HXValue* pValue;

            pValue = hx_entry_get_value(pPrefEntry);
            if(pValue)
            {
                strValue = hx_value_get_string(pValue);
                (*outBuffer)->Set((const UCHAR*)strValue, strlen(strValue) + 1);
                retVal = HXR_OK;
            }
            hx_entry_free(pPrefEntry);
        }
    }

    if(FAILED(retVal))
    {
        /* Override some r1signin required preferences */
        if(strcasecmp(pKey, "OrigCode") == 0)
        {
#warning FIXME
            (*outBuffer)->Set((const UCHAR*)"MAC01D", sizeof("MAC01D"));
            retVal = HXR_OK;
        }
    }    

    return retVal;
}
    
STDMETHODIMP CR1ClientPreferences::SetClientPreference( const char* pKey,
                                                         IHXBuffer* buffer )
{
    return SetClientPreferenceString( pKey, (const char*) buffer->GetBuffer() );    
}


STDMETHODIMP CR1ClientPreferences::SetClientPreferenceString( const char* pKey,
                                                              const char* pString )
{
    hxwindow_set_sign_in_property(m_pWindow,
                                  pKey,
                                  pString);

    return HXR_OK;
}


/* CR1ProductIdentity
 * ==================
 * Required for sign in
 */

#warning Fix the information in this class

class CR1ProductIdentity : public CUnknownIMP,
                           public IHXProductIdentity3
{
public:
    DECLARE_UNKNOWN( CR1ProductIdentity )
    
    // IRNProductIdentity
    STDMETHOD_(UINT32,GetMajorVersion) (THIS)
    {
        return TARVER_MAJOR_VERSION;
    }
    STDMETHOD_(UINT32,GetMinorVersion) (THIS)
    {
        return TARVER_MINOR_VERSION;
    }
    STDMETHOD_(UINT32,GetReleaseNumber) (THIS)
    {
        return (TARVER_ULONG32_VERSION & 0xFF000);
    }
    STDMETHOD_(UINT32,GetBuildNumber) (THIS)
    {
        return (TARVER_ULONG32_VERSION & 0xFFF);
    }
    STDMETHOD_(UINT32,GetLanguageId) (THIS)
    {
        return 0;
    }
    STDMETHOD(GetProductName) (THIS_ char* pName, UINT16 len)
    {
        return GetProductTitle( pName, len );
    }
    STDMETHOD(GetLanguageString) (THIS_ char* pLanguage, UINT16 len)
    {
        strncpy(pLanguage, "EN", len);
        return HXR_OK;
    }
    STDMETHOD(GetVersionString) (THIS_ char* pVersion, UINT16 len)
    {
        SafeStrCpy(pVersion, "0.0", len);
        return HXR_FAIL;
    }
    STDMETHOD(GetDistributionCode) (THIS_ char* pDistCode, UINT16 len)
    {
        SafeStrCpy(pDistCode, "HXPLAY", len);
        return HXR_FAIL;
    }
	
    // IRNProductIdentity2
    STDMETHOD(GetPath) (THIS_ char* /* pPath */ , UINT16 /* len */)
    {
        HX_ASSERT(0);
        return HXR_FAIL;
    }
    STDMETHOD(GetActiveWindow) (THIS_ REF(HXxWindowID) window)
    {
        window = 0;
        HX_ASSERT(0);
        return HXR_FAIL;
    }
    STDMETHOD(GetProductTitle) (THIS_ char* pTitle, UINT16 len)
    {
        SafeStrCpy(pTitle, "hxplay", len);
        return HXR_FAIL;
    }
    STDMETHOD_(BOOL,HasFeatures) (THIS_ UINT32 /* ulFeatures */)
    {
        return TRUE;
    }
    STDMETHOD(GetGUID) (THIS_ char* pGUID, UINT16 len)
    {
        memset( pGUID, 0, len );
        return HXR_OK;
    }
    
    // IRNProductIdentity3 -- should look for kRetailerCode as pProduct and return the proper code
    STDMETHOD(GetProductValue) (THIS_ const char* /* pProduct */, char* pReturnValue, UINT16 /* len */)
    {        
        *pReturnValue = '\0';
        return HXR_OK;
    }    
};


BEGIN_INTERFACE_LIST( CR1ProductIdentity )
INTERFACE_LIST_ENTRY_SIMPLE( IHXProductIdentity );
INTERFACE_LIST_ENTRY_SIMPLE( IHXProductIdentity2 );
INTERFACE_LIST_ENTRY_SIMPLE( IHXProductIdentity3 );
END_INTERFACE_LIST


/* CR1ProductIdentity
 * ==================
 * Required for sign in
 */
class CR1CommonClassFactory : public CUnknownIMP,
                              public IHXCommonClassFactory
{
public:
    DECLARE_UNKNOWN( CR1CommonClassFactory )

    // IHXCommonClassFactory
    STDMETHOD(CreateInstance) (THIS_ REFCLSID rclsid, void** ppUnknown)
    {
	return CreateInstanceAggregatable(rclsid, *(IUnknown**)ppUnknown, NULL);        
    }
    STDMETHOD(CreateInstanceAggregatable) (THIS_ REFCLSID rclsid, REF(IUnknown*)  ppUnknown, IUnknown* pUnkOuter);
};

HX_RESULT CR1CommonClassFactory::CreateInstanceAggregatable(REFCLSID rclsid, REF(IUnknown*)  ppUnknown, IUnknown* /* pUnkOuter */)
{
    ppUnknown = NULL;

    if (IsEqualCLSID(rclsid, CLSID_IHXBuffer))
    {
        IHXBuffer* pIBuffer = new CHXBuffer;
        ppUnknown = pIBuffer;
        ppUnknown->AddRef();
    }
    else if (IsEqualCLSID(rclsid, CLSID_TheProduct))
    {
        CR1ProductIdentity::CreateInstance( &ppUnknown );
    }
//     else if (IsEqualCLSID(rclsid, CLSID_R1CookieObserverManager))
//     {
//         CR1CookieObserverManager::CreateInstance( &ppUnknown );
//     }
	
    if (ppUnknown)
    {
        return HXR_OK;
    }
    else
    {
        HX_ASSERT(!"CR1CommonClassFactory needs to know how to make one of these");
        return HXR_FAIL;
    }
}

BEGIN_INTERFACE_LIST( CR1CommonClassFactory )
INTERFACE_LIST_ENTRY_SIMPLE( IHXCommonClassFactory );
END_INTERFACE_LIST

/* Sign in dialog handling
 * =======================
 */

typedef struct
{
    GladeXML* xml;
    gchar* username;
    gchar* password;
} HXSignInDialog;

G_CONST_RETURN gchar*
hxplay_sign_in_dialog_get_username(GtkDialog* dialog)
{
    HXSignInDialog* info = (HXSignInDialog*)g_object_get_data(G_OBJECT(dialog), "dialog_info");
    if(info)
    {
        return info->username;
    }

    return NULL;
}

G_CONST_RETURN gchar*
hxplay_sign_in_dialog_get_password(GtkDialog* dialog)
{
    HXSignInDialog* info = (HXSignInDialog*)g_object_get_data(G_OBJECT(dialog), "dialog_info");
    if(info)
    {
        return info->password;
    }

    return NULL;    
}

static void
hxplay_sign_in_dialog_destroy(GtkWidget* /* widget */,
                              HXSignInDialog* signin)
{
    glade_xml_destroy (signin->xml);

    g_free(signin->username);
    g_free(signin->password);
    g_free(signin);
}

static void
hxplay_sign_in_dialog_response(GtkWidget* dialog,
                               gint response_id,
                               HXSignInDialog* info)
{
    g_return_if_fail(info != NULL);
    g_return_if_fail(info->xml != NULL);
    
    if(response_id == GTK_RESPONSE_OK)
    {
        GtkWidget* username_entry;
        GtkWidget* password_entry;
        
        username_entry = glade_xml_get_widget(info->xml, "hsi_username");
        password_entry = glade_xml_get_widget(info->xml, "hsi_password");

        if(username_entry)
        {
            info->username = g_strdup(gtk_entry_get_text(GTK_ENTRY(username_entry)));
        }

        if(password_entry)
        {
            info->password = g_strdup(gtk_entry_get_text(GTK_ENTRY(password_entry)));
        }
    }
}


GtkDialog*
hxplay_sign_in_dialog_new(GdkWindow* parent)
{
    GladeXML* xml;
    GtkWidget* dialog;
    GtkWidget* username_entry; 
    GtkWidget* password_entry; 
    gint response;
    gchar *filename;
    HX_RESULT retVal;
    HXSignInDialog* info = NULL;

    g_return_if_fail(g_pR1ServiceAuthentication != NULL);
    
    filename = hxcommon_locate_file("signin.glade");
    xml = glade_xml_new (filename, NULL, NULL);
    g_free(filename);
    g_return_if_fail(xml != NULL);

    info = g_new0(HXSignInInfo, 1);
    info->xml = xml;
    
    /* We do transient setting this way so we can pop up this dialog
       from the embedded player, where we don't have a GtkWindow to
       work with. */
    g_signal_connect (G_OBJECT (dialog), "realize",
                      GTK_SIGNAL_FUNC (hxcommon_transient_parent_realized),
                      parent);

    g_signal_connect (G_OBJECT (dialog), "destroy",
                      G_CALLBACK (hxplay_sign_in_dialog_destroy),
                      info);

    g_signal_connect (G_OBJECT (dialog), "response",
                      G_CALLBACK (hxplay_sign_in_dialog_response),
                      info);

    return GTK_DIALOG(dialog);
}


G_CONST_RETURN gchar*
hxplay_sign_in_dialog_get_username (GtkDialog* dialog)
{
    
}

G_CONST_RETURN gchar*
hxplay_sign_in_dialog_get_password (GtkDialog* dialog)
{
    
}


/* Sign in init, destroy
 * =====================
 */

gboolean
sign_in_init(HXMainWindow* window)
{    
    GtkWidget* player;
    gboolean result;
    IUnknown* pUnk = NULL;
    HX_RESULT hxResult;
    IHXCommonClassFactory* pCCF;

    g_return_val_if_fail(g_pR1ServiceAuthentication == NULL, FALSE);
    g_return_val_if_fail(g_pR1ClientPreferences == NULL, FALSE);
    g_return_val_if_fail(g_pR1CommonClassFactory == NULL, FALSE);

    player = hxwindow_get_player(window);
    
    result = hx_player_get_unknown(HX_PLAYER(player), (void**)&pUnk);
    g_return_val_if_fail(result != FALSE, FALSE);

    g_pR1CommonClassFactory = new CR1CommonClassFactory;

    hxResult = g_pR1CommonClassFactory->QueryInterface(IID_IHXCommonClassFactory,
                                                       (void**)&pCCF);

//     hxResult = pUnk->QueryInterface(IID_IHXCommonClassFactory,
//                                     (void**)&pCCF);

    g_return_val_if_fail(pCCF && SUCCEEDED(hxResult), FALSE);
    
    g_pR1ClientPreferences = new CR1ClientPreferences;
    g_pR1ClientPreferences->Init(window, pCCF);
    
    g_pR1ServiceAuthentication =
        CR1ServiceAuthentication::CreateServiceAuthentication(pCCF,
                                                              g_pR1ClientPreferences);
    return TRUE;
}

void
sign_in_destroy(void)
{
    if(g_pR1ServiceAuthentication)
    {
        delete g_pR1ServiceAuthentication;
        g_pR1ServiceAuthentication = NULL;
    }
}
