#!/usr/bin/env perl

use strict;
use warnings;

use Glib;

use Glib::Object::Introspection;

Glib::Object::Introspection->setup(
    basename => 'GUPnP',
    version => '1.0',
    package => 'GUPnP',
    );


Glib::Object::Introspection->setup(
    basename => 'GSSDP',
    version => '1.0',
    package => 'GSSDP',
    );


my %control_points;

my $main_loop = Glib::MainLoop->new(undef, 0);

my $context_manager = GUPnP::ContextManager::create(0);

$context_manager->signal_connect('context-available' =>
				 \&on_context_available);

$context_manager->signal_connect('context-unavailable' =>
				 \&on_context_unavailable);

$main_loop->run;


sub on_context_available
{
    my ($context_manager, $context, $user_data) = @_;

    my $host_ip = $context->get_host_ip;

    print "UPnP Context becomes available $context ($host_ip)\n";

    my $control_point = GUPnP::ControlPoint->new($context, 'upnp:rootdevice');

    print "Control Point $control_point associated with $context\n";    

    $control_point->signal_connect('device-proxy-available' =>
                                   \&device_proxy_available);


    $control_point->signal_connect('device-proxy-unavailable' =>
                                   \&device_proxy_unavailable);


    $control_points{$context} = $control_point;

    GSSDP::ResourceBrowser::set_active($control_point, 1);
}


sub on_context_unavailable
{
    my ($context_manager, $context, $user_data) = @_;
    
    my $host_ip = $context->get_host_ip;

    print "UPnP Context becomes unavailable $context ($host_ip)\n";

    # Reference counting will destruct the control point
    delete $control_points{$context};
}


sub device_proxy_available
{
    my ($control_point, $device_proxy) = @_;

    my $device_udn  = $device_proxy->get_udn;
    my $device_name = $device_proxy->get_friendly_name;
    my $device_type = $device_proxy->get_device_type;

    print "Device becomes available: $device_name ($device_type) [$device_udn] $control_point\n";
}

sub device_proxy_unavailable
{
    my ($control_point, $device_proxy) = @_;

    my $device_udn  = $device_proxy->get_udn;
    my $device_name = $device_proxy->get_friendly_name;
    my $device_type = $device_proxy->get_device_type;

    print "Device becomes unavailable: $device_name ($device_type) [$device_udn] $control_point\n";
}
