package Plugins::RadioIO::Plugin;

# $Id: Plugin.pm 7196 2006-04-28 22:00:45Z andy $

# SlimServer Copyright (c) 2001-2007 Logitech
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# version 2.
#
# 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.

use strict;

use MIME::Base64;
use URI::Escape qw(uri_escape);

use Slim::Buttons::Common;
use Slim::Buttons::XMLBrowser;
use Slim::Player::ProtocolHandlers;
use Slim::Utils::Misc;
use Slim::Utils::Strings qw( string );
use Slim::Web::XMLBrowser;

my $FEED = 'http://www.squeezenetwork.com/api/radioio/opml';
my $cli_next;

sub enabled {
	return ($::VERSION ge '6.3');
}                             

sub initPlugin {
	$::d_plugins && msg("RadioIO Plugin initializing.\n");

	Slim::Buttons::Common::addMode('PLUGIN.RadioIO', getFunctions(), \&setMode);

#        |requires Client
#        |  |is a Query
#        |  |  |has Tags
#        |  |  |  |Function to call
#        C  Q  T  F
    Slim::Control::Request::addDispatch(['radioio', 'items', '_index', '_quantity'],
        [0, 1, 1, \&cliQuery]);
	Slim::Control::Request::addDispatch(['radioio', 'playlist', '_method' ],
		[1, 1, 1, \&cliQuery]);
	$cli_next=Slim::Control::Request::addDispatch(['radios', '_index', '_quantity' ],
		[0, 1, 1, \&cliRadiosQuery]);
}

sub addMenu {
	return 'RADIO';
}

sub getDisplayName {
	return 'PLUGIN_RADIOIO_MODULE_NAME';
}

sub getFunctions {
	return {};
}

sub setMode {
	my $client = shift;
	my $method = shift;

	if ($method eq 'pop') {

		Slim::Buttons::Common::popMode($client);
		return;
	}

	# use INPUT.Choice to display the list of feeds
	my %params = (
		header   => 'PLUGIN_RADIOIO_LOADING',
		modeName => 'RadioIO Plugin',
		url      => radioIOURL($client),
		title    => $client->string(getDisplayName()),
	);

	Slim::Buttons::Common::pushMode($client, 'xmlbrowser', \%params);

	# we'll handle the push in a callback
	$client->param('handledTransition',1);
}

sub radioIOURL {
	my $client = shift;
	
	my $username = Slim::Utils::Prefs::get('plugin_radioio_username');
	my $password = Slim::Utils::Prefs::get('plugin_radioio_password');
	
	my $url = $FEED;
	
	if ( $username && $password ) {
		$url .= '?username=' . uri_escape($username) . '&password=' . uri_escape( decode_base64( $password ) );
	}
	
	return $url;
}

# Web pages

sub webPages {
	my $title = 'PLUGIN_RADIOIO_MODULE_NAME';
	
	if (grep {$_ eq 'RadioIO::Plugin'} Slim::Utils::Prefs::getArray('disabledplugins')) {
		Slim::Web::Pages->addPageLinks('radio', { $title => undef });
	} else {
		Slim::Web::Pages->addPageLinks('radio', { $title => 'plugins/RadioIO/index.html' });
	}
	
	my %pages = ( 
		'index.html' => sub {
			my $client = $_[0];
			my $url = radioIOURL($client);
			Slim::Web::XMLBrowser->handleWebIndex( {
				feed   => $url,
				title  => $title,
				args   => \@_
			} );
		},
	);
	
	return \%pages;
}

sub cliQuery {
	my $request = shift;
	
	$::d_plugins && msg("RadioIO: cliQuery()\n");
	
	Slim::Buttons::XMLBrowser::cliQuery('radioio', radioIOURL(), $request);
}

sub cliRadiosQuery {
	my $request = shift;
	
	$::d_plugins && msg("RadioIO: cliRadiosQuery()\n");
	
	# what we want the query to report about ourself
	my $data = {
		'cmd' => 'radioio',                    # cmd label
		'name' => Slim::Utils::Strings::string(getDisplayName()),  # nice name
		'type' => 'xmlbrowser',              # type
	};
	
	# let our super duper function do all the hard work
	Slim::Control::Queries::dynamicAutoQuery($request, 'radios', $cli_next, $data);
}

sub setupGroup {
	my %Group = (
		PrefOrder => [
			'plugin_radioio_username',
			'plugin_radioio_password',
		],
		GroupHead => string( 'PLUGIN_RADIOIO_MODULE_NAME' ),
		GroupDesc => string( 'SETUP_GROUP_PLUGIN_RADIOIO_DESC' ),
		GroupLine => 1,
		GroupSub  => 1,
		Suppress_PrefSub  => 1,
		Suppress_PrefLine => 1,
	);

	my %Prefs = (
		plugin_radioio_username => {},
		plugin_radioio_password => { 
			onChange => sub {
				my $encoded = encode_base64( $_[1]->{plugin_radioio_password}->{new} );
				chomp $encoded;
				Slim::Utils::Prefs::set( 'plugin_radioio_password', $encoded );
			},
			inputTemplate => 'setup_input_passwd.html',
			changeMsg     => string('SETUP_PLUGIN_RADIOIO_PASSWORD_CHANGED')
		},
	);

	return( \%Group, \%Prefs );
}

sub strings
{
	return "
PLUGIN_RADIOIO_MODULE_NAME
	DE	radioio.com
	FR	radioio.com
	IT	radioio.com
	ES	radioio.com
	NL	radioio.com
	EN	radioio.com - no boundaries.
	HE	radioio.com - ללא גבולות.

PLUGIN_RADIOIO_MODULE_TITLE
	DE	radioio.com
	EN	radioio.com
	ES	radioio.com
	FR	radioio.com
	HE	radioio.com
	IT	radioio.com
	NL	radioio.com

PLUGIN_RADIOIO_LOADING
	DE	RadioIO wird geladen ...
	EN	Loading RadioIO...
	ES	Cargando RadioIO…
	FR	Chargement RadioIO...
	HE	טוען את RadioIO...
	IT	Caricamento RadioIO in corso…
	NL	RadioIO wordt geladen...

SETUP_GROUP_PLUGIN_RADIOIO_DESC
	DE	Wenn Sie ein RadioIO-Konto haben, geben Sie Benutzername und Kenwort ein. <a href='http://www.radioio.com/registration.php' target='_new'>Registrierte Benutzer</a> erhalten qualitativ hochwertige Datenströme bei 128kb/s und <a href='http://www.radioio.com/membership.php' target='_new'>SoundPass-Mitglieder</a> haben Zugriff auf werbefreie Ströme.
	EN	If you have a RadioIO account, enter your username and password. <a href='http://www.radioio.com/registration.php' target='_new'>Registered members</a> get high quality 128k streams, and <a href='http://www.radioio.com/membership.php' target='_new'>SoundPass members</a> have access to high quality, commercial-free streams.
	ES	Si tiene una cuenta RadioIO, introduzca su nombre de usuario y su contraseña. <a href='http://www.radioio.com/membership.php' target='_new'>Lo miembros registrados</a> obtienen secuencias de alta calidad a 128 kbps, y los <a href='http://www.radioio.com/membership.php' target='_new'>miembros de SoundPass</a> tienen acceso a secuencias de alta calidad sin anuncios.
	FR	Si vous possédez un compte RadioIO, saisissez votre nom d'utilisateur et votre mot de passe. <a href='http://www.radioio.com/membership.php' target='_new'>Les membres enregistrés</a> bénéficient de flux haute qualité 128 Ko et <a href='http://www.radioio.com/membership.php' target='_new'>les membres de SoundPass</a> ont accès à des flux de haute qualité sans publicités.
	HE	אם יש ברשותך חשבון RadioIO, הזן את שם המשתמש והסיסמה. <a href='http://www.radioio.com/registration.php' target='_new'>חברים רשומים</a> מקבלים זרימות באיכות גבוהה של 128k ול<a href='http://www.radioio.com/membership.php' target='_new'>חברים בעלי חשבון SoundPass</a> יש גישה לזרימות באיכות גבוהה ללא פרסומות.
	IT	Se si dispone di un account RadioIO, immettere il nome utente e la password. <a href='http://www.radioio.com/membership.php' target='_new'>Gli utenti registrati</a> possono ascoltare trasmissioni di alta qualità a 128 k mentre <a href='http://www.radioio.com/membership.php' target='_new'>gli utenti SoundPass</a> hanno accesso a trasmissioni di alta qualità e senza interruzioni pubblicitarie.
	NL	Als je een RadioIO-abonnement hebt, voer je je gebruikersnaam en wachtwoord in. <a href='http://www.radioio.com/membership.php' target='_new'>Geregistreerde abonnees</a> krijgen hoogwaardige 128k audio, en <a href='http://www.radioio.com/membership.php' target='_new'>SoundPass abonnees</a> hebben toegang tot hoogwaardige audio zonder advertenties.

SETUP_PLUGIN_RADIOIO_USERNAME
	DE	RadioIO-Benutzername
	EN	RadioIO Username
	ES	Nombre de usuario de RadioIO
	FR	Nom d'utilisateur RadioIO
	HE	שם משתמש עבור RadioIO
	IT	Nome utente RadioIO
	NL	RadioIO-gebruikersnaam

SETUP_PLUGIN_RADIOIO_USERNAME_DESC
	DE	Ihr RadioIO-Benutzername. Melden Sie sich bei <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> an.
	EN	Your RadioIO username, visit <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> to sign up
	ES	Su nombre de usuario de RadioIO, visite <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> para registrarse
	FR	Votre nom d'utilisateur RadioIO (visitez <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> pour vous inscrire):
	HE	שם המשתמש שלך עבור RadioIO, עבור לכתובת <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> כדי להירשם
	IT	Nome utente in RadioIO. Per eseguire la registrazione, accedere a <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a>.
	NL	Je RadioIO-gebruikersnaam. Ga naar <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> om je aan te melden.

SETUP_PLUGIN_RADIOIO_PASSWORD
	DE	RadioIO-Kennwort
	EN	RadioIO Password
	ES	Contraseña para RadioIO
	FR	Mot de passe RadioIO
	HE	סיסמה עבור RadioIO
	IT	Password per RadioIO
	NL	RadioIO-wachtwoord

SETUP_PLUGIN_RADIOIO_PASSWORD_DESC
	DE	Ihr RadioIO-Kennwort
	EN	Your RadioIO password
	ES	Su contraseña para RadioIO
	FR	Votre mot de passe RadioIO
	HE	הסיסמה שלך עבור RadioIO
	IT	Password per RadioIO
	NL	Je RadioIO-wachtwoord

SETUP_PLUGIN_RADIOIO_PASSWORD_CHANGED
	DE	Das RadioIO-Kennwort wurde geändert
	EN	Your RadioIO password has been changed
	ES	Se ha cambiado la contraseña para RadioIO
	FR	Votre mot de passe RadioIO a été modifié
	HE	הסיסמה עבור RadioIO השתנתה
	IT	La password RadioIO è stata modificata
	NL	Je RadioIO-wachtwoord is gewijzigd
";}

1;
