/**
 * GMyth Library
 *
 * @file gmyth/gmyth_upnp.c
 * 
 * @brief <p> GMythUPnP allows that a MythTV frontend discovers a 
 * MythTV backend, using the UPnP architecture.
 *
 * Copyright (C) 2006 INdT - Instituto Nokia de Tecnologia.
 * @author Rosfran Lins Borges <rosfran.borges@indt.org.br>
 *
 *//*
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser 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 Lesser 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
 *   
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gmyth_upnp.h"

#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>

#include <gmyth/gmyth_backendinfo.h>
#include <gmyth/gmyth_socket.h>
#include <gmyth/gmyth_uri.h>
#include <gmyth/gmyth_debug.h>

#define GMYTH_UPNP_MAX_SEARCHS		10

static void gmyth_upnp_class_init          (GMythUPnPClass *klass);
static void gmyth_upnp_init                (GMythUPnP *object);

static void gmyth_upnp_dispose  (GObject *object);
static void gmyth_upnp_finalize (GObject *object);

static gboolean gmyth_upnp_initialize ( GMythUPnP *gmyth_upnp, GMythBackendInfo *gmyth_backend_info );

static gboolean gmyth_upnp_print_cp_device_list( CgUpnpControlPoint* controlPt, gchar **udn, 
						GList **mythtv_servers_lst );

G_DEFINE_TYPE(GMythUPnP, gmyth_upnp, G_TYPE_OBJECT)

static GStaticMutex mutex = G_STATIC_MUTEX_INIT;

static void
gmyth_upnp_class_init (GMythUPnPClass *klass)
{
	GObjectClass *gobject_class;

	gobject_class = (GObjectClass *) klass;

	gobject_class->dispose  = gmyth_upnp_dispose;
	gobject_class->finalize = gmyth_upnp_finalize;	
}

static void
gmyth_upnp_init ( GMythUPnP *gmyth_upnp )
{
	gmyth_upnp->upnp_dev_found = FALSE;
	
	gmyth_upnp->uri = NULL;
	gmyth_upnp->host = NULL;
	gmyth_upnp->port = 0;
	gmyth_upnp->protocol = NULL;
	
	gmyth_upnp->gmyth_backend_info = NULL;
	
	gmyth_upnp->control_point = NULL;
	
}

/** Creates a new instance of GMythUPnP.
 * 
 * @return a new instance of GMythUPnP. 
 */
GMythUPnP *
gmyth_upnp_new ( GMythBackendInfo *gmyth_backend_info ) 
{
    GMythUPnP *gmyth_upnp = GMYTH_UPNP (g_object_new (GMYTH_UPNP_TYPE, NULL));
    
    gmyth_upnp->gmyth_backend_info = gmyth_backend_info;
    
    if ( !gmyth_upnp_initialize ( gmyth_upnp, gmyth_backend_info ) )
    	return NULL;
    
    return gmyth_upnp;
}

static void
gmyth_upnp_dispose  (GObject *object)
{
	GMythUPnP *gmyth_upnp = GMYTH_UPNP(object);

	if ( gmyth_upnp->control_point != NULL ) {
		cg_upnp_controlpoint_stop( gmyth_upnp->control_point );
		cg_upnp_controlpoint_delete( gmyth_upnp->control_point );
		gmyth_upnp->control_point = NULL;
	}

	if ( gmyth_upnp->uri != NULL ) {
		g_free ( gmyth_upnp->uri );
		gmyth_upnp->uri = NULL;
	}
	
	if ( gmyth_upnp->host != NULL ) {
		g_free ( gmyth_upnp->host );
		gmyth_upnp->host = NULL;
	}
	
	if ( gmyth_upnp->protocol != NULL ) {
		g_free ( gmyth_upnp->protocol );
		gmyth_upnp->protocol = NULL;
	}
	
	if ( gmyth_upnp->mythtv_servers != NULL )	{
		g_list_free( gmyth_upnp->mythtv_servers );
		gmyth_upnp->mythtv_servers = NULL;
	}
	
	G_OBJECT_CLASS (gmyth_upnp_parent_class)->dispose (object);
}

static void
gmyth_upnp_finalize (GObject *object)
{
	g_signal_handlers_destroy (object);

	G_OBJECT_CLASS (gmyth_upnp_parent_class)->finalize (object);
}

/**
 * Create a control point and start it.
 */
static gboolean
gmyth_upnp_initialize ( GMythUPnP *gmyth_upnp, GMythBackendInfo *gmyth_backend_info )
{
	
	gboolean ret = FALSE;
	
	GMythURI* uri = NULL;
	
	guint iter_count = GMYTH_UPNP_MAX_SEARCHS;
	
	g_return_val_if_fail( gmyth_backend_info != NULL, FALSE );
	
	/* Create the cybergarage control point */
	gmyth_upnp->control_point = cg_upnp_controlpoint_new();
	/* cg_upnp_controlpoint_setdevicelistener( gmyth_upnp->control_point, device_listener ); */
	
	/* Start the control point */
  if ( cg_upnp_controlpoint_start( gmyth_upnp->control_point ) == FALSE)
	{
	  gmyth_debug( "Unable to start UPnP control point!!!" );
	  goto done;
  }
	else
	{
    gmyth_debug( "Control point started." );
	}
	
	while ( gmyth_upnp->upnp_dev_found == FALSE && ( --iter_count > 0 ) ) {
		
		gmyth_debug( "UPnP MythTV Client control point is searching MythTV AV Device server...\n" );
       
		if ( gmyth_upnp->control_point != NULL )
			cg_upnp_controlpoint_search ( gmyth_upnp->control_point, 
		        		"urn:schemas-upnp-org:service:ContentDirectory:1" );

		/* just to avoid clinkc pthread concurrency faults */
		cg_wait( 1000 );
		
		/* discover if it was found */
		gmyth_upnp->upnp_dev_found = gmyth_upnp_print_cp_device_list( gmyth_upnp->control_point, &gmyth_upnp->udn,
									&gmyth_upnp->mythtv_servers );
		
	}
	
	if ( gmyth_upnp->upnp_dev_found ) {
		
		gmyth_debug( "Found UPnP MythTV AV Device...\n" );
		
		if ( g_list_first( gmyth_upnp->mythtv_servers ) != NULL && (g_list_first( gmyth_upnp->mythtv_servers ))->data != NULL )
		{
			gmyth_upnp->uri = (gchar*) (g_list_first( gmyth_upnp->mythtv_servers ))->data;
			uri = gmyth_uri_new_with_value( gmyth_upnp->uri );
			
			gmyth_upnp->host = gmyth_uri_get_host( uri );
			gmyth_upnp->port = gmyth_uri_get_port( uri );
			gmyth_upnp->protocol = gmyth_uri_get_protocol( uri );
			
			/* sets all the discovered data from the UPnP remote device, like host name, IP address, port,... */
			if ( NULL != gmyth_upnp->host )
				gmyth_backend_info_set_hostname ( gmyth_upnp->gmyth_backend_info, gmyth_upnp->host );
			
			if ( gmyth_upnp->port > 0 )
				 gmyth_backend_info_set_port ( gmyth_upnp->gmyth_backend_info, gmyth_upnp->port );
				 
			ret = TRUE;
		}
	}	

done:

  if ( uri != NULL )
  {
  	g_object_unref( uri );
  	uri = NULL;
  }  	

	return ret;
	
}

/** 
 * Prints the Control Point's device list
 */
static gboolean
gmyth_upnp_print_cp_device_list( CgUpnpControlPoint* controlPt, gchar **udn, GList **mythtv_servers_lst )
{
	
	g_return_val_if_fail( mythtv_servers_lst != NULL, FALSE );	
	g_return_val_if_fail( controlPt != NULL, FALSE );
	
	gchar* mythtvFriendlyName = "Myth";
	/* begin assertion about the size of discovered devices */
	gint numDevices = cg_upnp_controlpoint_getndevices(controlPt);
	gint cntDevs = 0;	
	//CgUpnpDeviceList *devList = NULL;
	CgUpnpDevice *childDev;
	gchar *devName = NULL, *dev_url = NULL;
	gboolean upnp_dev_found = FALSE;
	
	gmyth_debug( "UPnP MythTV AV Device list size = %d\n", numDevices );
	
	for ( childDev = cg_upnp_controlpoint_getdevices(controlPt); childDev != NULL; 
			childDev = cg_upnp_device_next(childDev) ) {
		devName = cg_upnp_device_getfriendlyname(childDev);
		dev_url = cg_upnp_device_getlocationfromssdppacket( childDev );
		gmyth_debug( "Device's friendly name = %s, and  device's URL = %s\n", devName, dev_url );
		if ( ( upnp_dev_found = ( g_strstr_len( devName, strlen( devName ), mythtvFriendlyName ) != NULL ) ) == TRUE ) 
		{
			*udn = cg_upnp_device_getudn( childDev );
			*mythtv_servers_lst = g_list_append( *mythtv_servers_lst, dev_url ); 
		}
		++cntDevs;
	}
	
	if ( upnp_dev_found == TRUE ) {
		gmyth_debug( "MythTV AV Device found, from a total of %d devices.\n", cntDevs );
	} else if ( numDevices == cntDevs ) {
		gmyth_debug( "MythTV AV Device not found, from a total of %d devices.\n", cntDevs );
	} else {
		gmyth_debug( "Control Point's MythTV AV Device count is wrong: iterated over %d devices, but there are %d registered devices.\n", cntDevs, numDevices );
	}
	
	return upnp_dev_found;

}

/** Gets the GMythBackendInfo host object associated to this upnp.
 * 
 * @return The string host object currently valid or NULL if the settings
 * were not opened.
 */
gchar*
gmyth_upnp_get_host ( GMythUPnP *gmyth_upnp )
{
	
	if ( NULL == gmyth_upnp || NULL == gmyth_upnp->host ) 
	{
		gmyth_debug ("[%s] GMythUPnP host field not initialized\n", __FUNCTION__);
		return NULL;
	}

	return gmyth_upnp->host;
}

/** Gets the GMythBackendInfo port object associated to this upnp.
 * 
 * @return The string object currently valid or NULL if the port number.
 */
gint
gmyth_upnp_get_port( GMythUPnP *gmyth_upnp )
{

	if ( NULL == gmyth_upnp || gmyth_upnp->port <= 0 ) 
	{
		gmyth_debug ("[%s] GMythUPnP host field not initialized\n", __FUNCTION__);
		return 0;
	}

	return gmyth_upnp->port;
}

/** Gets the UPnP AV devices server's list associated to this upnp.
 * 
 * @return The GList* containing all the URI values for each recognized UPnP device,
 * 			or NULL if it couldn't recognize any MythTV AV device.
 */
GList*
gmyth_upnp_get_servers ( GMythUPnP *gmyth_upnp )
{
	
	if ( NULL == gmyth_upnp || NULL == gmyth_upnp->mythtv_servers ) 
	{
		gmyth_debug ("[%s] GMythUPnP has no MythTV servers recognized.\n", __FUNCTION__);
		return NULL;
	}

	return gmyth_upnp->mythtv_servers;
}

/** Gets the GMythBackendInfo object associated to this upnp.
 * 
 * @return The GMythBackendInfo object currently valid or NULL if the settings
 * were not opened.
 */
GMythBackendInfo*
gmyth_upnp_get_backend_info ( GMythUPnP *gmyth_upnp )
{
	
	if ( NULL == gmyth_upnp || NULL == gmyth_upnp->gmyth_backend_info ) 
	{
		gmyth_debug ("[%s] GMythUPnP not initialized\n", __FUNCTION__);
		return NULL;
	}

	return gmyth_upnp->gmyth_backend_info;
}