package Plugins::RadioTime::Plugin;

# $Id: Plugin.pm 12027 2007-05-16 19:05:27Z mherger $

# 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 URI::Escape qw(uri_escape);

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

my $FEED = 'http://opml.radiotime.com/Index.aspx';
my $cli_next;

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

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

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

#        |requires Client
#        |  |is a Query
#        |  |  |has Tags
#        |  |  |  |Function to call
#        C  Q  T  F
    Slim::Control::Request::addDispatch(['radiotime', 'items', '_index', '_quantity'],
        [0, 1, 1, \&cliQuery]);
	Slim::Control::Request::addDispatch(['radiotime', '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_RADIOTIME_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_RADIOTIME_LOADING',
		modeName => 'RadioTime Plugin',
		url      => radioTimeURL($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 radioTimeURL {
	my $client = shift;
	
	my $username;
	
	if ( $ENV{SLIM_SERVICE} ) { # SqueezeNetwork
		$username = $client->prefGet('plugin_radiotime_username', undef, 1);
	}
	else {
		$username = Slim::Utils::Prefs::get('plugin_radiotime_username');
	}
	
	my $url = $FEED;
	
	if ( $username ) {
		$url .= '?username=' . uri_escape($username);
	}
	
	# RadioTime's listing defaults to giving us mp3 and wma streams.
	# If AlienBBC is installed we can ask for Real streams too.
	if ( exists $INC{'Plugins/Alien/Plugin.pm'} ) {
		$url .= ( $url =~ /\?/ ) ? '&' : '?';
		$url .= 'Filters=mp3,wma,real';
	}
	
	return $url;
}

# Web pages

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

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

sub cliRadiosQuery {
	my $request = shift;
	
	$::d_plugins && msg("RadioTime: cliRadiosQuery()\n");
	
	# what we want the query to report about ourself
	my $data = {
		'cmd' => 'radiotime',                    # 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_radiotime_username',
		],
		GroupHead => string( 'PLUGIN_RADIOTIME_MODULE_NAME' ),
		GroupDesc => string( 'SETUP_GROUP_PLUGIN_RADIOTIME_DESC' ),
		GroupLine => 1,
		GroupSub  => 1,
		Suppress_PrefSub  => 1,
		Suppress_PrefLine => 1,
	);

	my %Prefs = (
		plugin_radiotime_username => {},
	);

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

sub strings
{
	return qq^
PLUGIN_RADIOTIME_MODULE_NAME
	DE	Radioverzeichnis - RadioTime
	EN	Radio Guide - RadioTime
	ES	Guía de radio - RadioTime
	FR	Guide des radios - RadioTime
	HE	RadioTime
	IT	Programmazione radio - RadioTime
	NL	Radiogids - RadioTime

PLUGIN_RADIOTIME_MODULE_TITLE
	DE	RadioTime
	EN	radiotime
	ES	radiotime
	FR	radiotime
	HE	radiotime
	IT	radiotime
	NL	radiotime

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

SETUP_GROUP_PLUGIN_RADIOTIME_DESC
	DE	Auf <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> können Sie die interessantesten lokalen und globalen Radiosender suchen: Wort, Sport, Musik oder Religion - alles <b>gratis</b>.
	EN	Use <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> to find your favorite local and global talk, sports, religious, and music radio — all <b>free</b>.
	ES	Use <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> para encontrar sus emisoras de radio favoritas de debate, deportes, religión y música tanto locales como internacionales. Y <b>gratis</b>.
	FR	Parcourez <b>gratuitement</b> <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> pour trouver vos stations préférées: infos, sport, musique, etc.
	HE	השתמש באתר <a href='http://www.radiotime.com'
	IT	In <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> sono disponibili canali <b>gratuiti</b> di sport, religione, discussione e musica sia locali che internazionali.
	NL	Gebruik <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> om je favoriete lokale en globale religieuze, praat-, sport- en muziekradio te vinden — allemaal<b>gratis</b>.

SETUP_PLUGIN_RADIOTIME_USERNAME
	DE	Geben Sie Ihren RadioTime-Benutzernamen ein.
	EN	Enter your RadioTime username.
	ES	Introduzca el nombre de usuario de RadioTime.
	FR	Spécifiez votre nom d'utilisateur RadioTime
	HE	הזן את שם המשתמש שלך עבור RadioTime.
	IT	Immettere il nome utente RadioTime.
	NL	Voer je RadioTime-gebruikersnaam in.

SETUP_PLUGIN_RADIOTIME_USERNAME_DESC
	DE	Melden Sie sich bei <a href='http://www.radiotime.com' target='_new'>radiotime.com</b> <b>kostenlos</b> an. Fügen Sie Sender oder Sendungen zu ihrer 'My Radio'-Liste hinzu und geben Sie sie auf Squeezebox oder Transporter wieder.
	EN	Visit <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> to sign up for <b>free</b>.  Add stations and shows to My Radio then listen on your Squeezebox or Transporter.
	ES	Visite <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> para registrarse <b>gratis</b>. Agregue emisoras y programas a Mi radio y escuche en Squeezebox o Transporter.
	FR	Inscrivez-vous <b>gratuitement</b> sur <a href='http://www.radiotime.com' target='_new'>radiotime.com</a>. Ajoutez des stations et des émissions à votre liste et écoutez-les sur la Squeezebox ou sur Transporter.
	HE	עבור לכתובת <a href='http://www.radioio.com/registration.php' target='_new'>radioio.com</a> כדי להירשם ללא תשלום. הוסף תחנות ותוכניות ל'הרדיו שלי' ולאחר מכן האזן להן בנגן Squeezebox או Transporter שברשותך.
	IT	Per eseguire la registrazione <b>gratuita</b>, accedere a <a href='http://www.radiotime.com' target='_new'>radiotime.com</a>. È possibile aggiungere stazioni e programmi a My Radio (La mia radio) e ascoltarli su Squeezebox o Transporter.
	NL	Ga naar <a href='http://www.radiotime.com' target='_new'>radiotime.com</a> om je <b>gratis</b> aan te melden. Voeg stations en programma's toe aan 'My Radio' en luister ernaar op je Squeezebox of Transporter.
^;}

1;
