#!/usr/bin/perl -w

# IMPORTANT: The retrieved tariff data may only be used by the LCR plugin
# showing the logo and the URL www.teltarif.de as their source.

# WICHTIG: Die bezogenen Tarifdaten dürfen nur für die Anzeige im LCR Plugin,
# mit Einblendung des Logos und der URL www.teltarif.de als Quelle, verwendet werden.

use strict;
use warnings;

{
	# since this is the only service I use, only this parser is implemented
	# however, feel free to implement your own ones taking this as template (see below
	# this package for details).
	# if you do so, please let me know and I will include the new parser.
	# be aware that I did not test the support for additional parsers, please
	# report bugs you encounter!
	package TeltarifParser;
	use base 'HTML::Parser';
	use LWP::Simple;

	my $url = "http://www.telefontarife.de/";
	my $content = get($url);

	my $target_counter = 0;
	my $line_counter = 0;

	# the names given here are displayed in the osd - identifying each line
	# the names should not be longer than the ones that can be seen below
	# notice: more than 7 targets are not displayed in the vdr-osd
	my @targets = ( "City", "Nah", "Fern", "D1", "D2", "E-Plus", "O2" );

	# pVariable (p stands for pattern), these are the triggers for the parser
	my $pcity		= '<!-- City-Tarif -->';
	my $pregio50		= '<!-- Regio 50 Tarif -->';
	my $pfern		= '<!-- Fern Tarif -->';

	my $pd1			= '<!-- D1-Netz -->';
	my $pd2			= '<!-- D2-Netz -->';
	my $peplus		= '<!-- E-Plus-Netz -->';
	my $po2			= '<!-- O2-Netz -->';

	my $comment_start = "false";
	my $tmp = 0;

	# specify events here rather than in a subclass
	my $p = HTML::Parser->new( api_version => 3,
		 start_h	=> [\&start,"tagname, attr, attrseq, text"],
		 end_h		=> [\&end,"tagname, text"],
		 text_h		=> [\&text,"text, is_cdata"],
		 comment_h	=> [\&comment,"event, text"]
	#         default_h   => [sub { print shift }, "text"],
	       );

	# Remove whitespace from the start and end of the string
	sub trim($)
	{
		my $string = shift;
		$string =~ s/^\s+//;
		$string =~ s/\s+$//;
		$string =~ s/\n+$//;
		return $string;
	}

	sub comment
	{
		my($self, $comment) = @_;
		
		if ( $comment eq $pcity  )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pregio50 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pfern )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pd1 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pd2 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $peplus )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $po2 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		
	}       
	sub start
	{
		my ($tag, $attr, $attrseq, $origtext) = @_;
	  
	#      unless ($tag =~ /^a$/) {
	#          print $origtext;
	#          return;
		if ( ( $tag =~ /^b$/ ) ) {
			return;
		}
	  }
	sub end {
		my($tagname, $origtext) = @_;
		
		# the provider's number is printed in bold
		if ( ( $tagname =~ /^b$/ ) && ( $comment_start eq "true" ) ) {
			$comment_start = "false";
			$line_counter = 1;
			return;
		}
	}

	sub text {
		my($text, $is_cdata) = @_;
		my @result;
		# find the telephone number for the provider
		if ( $text =~ /\d/ && ( $comment_start eq "true" ) )
		{
	#		print $targets[$target_counter-1],": ",$text,"\n";
			print $targets[$target_counter-1],"\n";
			print $text,"\n";
			$line_counter++;
			return;
		}
		if ( $line_counter == 1 )
		{
			# get rid of the newlines
			@result = split( /\n+/, $text);
			$text = $result[1];
			# get rid of the hard-coded html whitespace
			$text =~ s/&nbsp;/ /s;
	#		print "Preis: ",$text,"\n";
			print $text,"\n";
			$line_counter++;
		}
		elsif ( $line_counter == 2 )
		{
			# get rid of the newlines
			@result = split( /\n+/, $text);
			$result[1] = substr($result[1], 0, length($result[1])-5);
	#		print "Takt: ",$result[1],"\n";
			print $result[1],"\n";
			$line_counter++;
		}
		# not interested in more lines, we have all our information
		if ( $line_counter gt 2 )
		{
			$line_counter = 0;
		}
	}

	sub parseContent {
		$p->parse($content);
	}
}
############## ANOTHER PARSER ######################################################
{
	# take this and change it to your needs to implement another parser
	package YourParser;
	use base 'HTML::Parser';
	use LWP::Simple;

	my $url = "http://www.your-data-provider.com/";
	my $content = get($url);

	my $target_counter = 0;
	my $line_counter = 0;

	# the names given here are displayed in the osd - identifying distances/mobile providers
	# each line
	# the names should not be longer than the ones that can be seen below
	# notice: more than 7 targets are not displayed in the vdr-osd
	my @targets = ( "City", "Near", "Far", "Intern.", "Mob1", "Mob2", "Mob3" );

	# pVariable (p stands for pattern), these are the triggers for the parser
	# this is something you definitely have to adjust
	my $pcity		= '<!-- City-Tarif -->';
	my $pregio50		= '<!-- Regio 50 Tarif -->';
	my $pfern		= '<!-- Fern Tarif -->';

	my $pd1			= '<!-- D1-Netz -->';
	my $pd2			= '<!-- D2-Netz -->';
	my $peplus		= '<!-- E-Plus-Netz -->';
	my $po2			= '<!-- O2-Netz -->';

	my $comment_start = "false";
	my $tmp = 0;

	# specify events here rather than in a subclass
	my $p = HTML::Parser->new( api_version => 3,
		 start_h	=> [\&start,"tagname, attr, attrseq, text"],
		 end_h		=> [\&end,"tagname, text"],
		 text_h		=> [\&text,"text, is_cdata"],
		 comment_h	=> [\&comment,"event, text"]
	#         default_h   => [sub { print shift }, "text"],
	       );

	# Remove whitespace from the start and end of the string
	sub trim($)
	{
		my $string = shift;
		$string =~ s/^\s+//;
		$string =~ s/\s+$//;
		$string =~ s/\n+$//;
		return $string;
	}

	sub comment
	{
		my($self, $comment) = @_;
		
		# after the occurence of each pattern, set the corresponding
		# flag to true
		if ( $comment eq $pcity  )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pregio50 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pfern )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pd1 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $pd2 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $peplus )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		if ( $comment eq $po2 )
		{
			$comment_start = "true";
			$target_counter++;
		}
		
		
	}       
	sub start
	{
		my ($tag, $attr, $attrseq, $origtext) = @_;
	  
	#      unless ($tag =~ /^a$/) {
	#          print $origtext;
	#          return;
		if ( ( $tag =~ /^b$/ ) ) {
			return;
		}
	  }
	sub end {
		my($tagname, $origtext) = @_;
		
		# the provider's number is printed in bold
		# this might be different in your case!
		if ( ( $tagname =~ /^b$/ ) && ( $comment_start eq "true" ) ) {
			$comment_start = "false";
			$line_counter = 1;
			return;
		}
	}

	sub text {
		# this is something you might have to adjust to your needs as well
		# since your data may not be formatted the same way as the data
		# provided by www.teltarif.de.
		my($text, $is_cdata) = @_;
		my @result;
		# find the telephone number for the provider
		if ( $text =~ /\d/ && ( $comment_start eq "true" ) )
		{
	#		print $targets[$target_counter-1],": ",$text,"\n";
			print $targets[$target_counter-1],"\n";
			print $text,"\n";
			$line_counter++;
			return;
		}
		if ( $line_counter == 1 )
		{
			# get rid of the newlines
			@result = split( /\n+/, $text);
			$text = $result[1];
			# get rid of the hard-coded html whitespace
			$text =~ s/&nbsp;/ /s;
	#		print "Preis: ",$text,"\n";
			print $text,"\n";
			$line_counter++;
		}
		elsif ( $line_counter == 2 )
		{
			# get rid of the newlines
			@result = split( /\n+/, $text);
			$result[1] = substr($result[1], 0, length($result[1])-5);
	#		print "Takt: ",$result[1],"\n";
			print $result[1],"\n";
			$line_counter++;
		}
		# not interested in more lines, we have all our information
		if ( $line_counter gt 2 )
		{
			$line_counter = 0;
		}
	}

	sub parseContent {
		$p->parse($content);
	}
}

# this is where the correct parser is chosen
if ( !defined $ARGV[0] || $ARGV[0] eq "teltarif" )
{
	TeltarifParser->parseContent();
#	print "Got teltarif-data\n";
}
elsif ( $ARGV[0] eq "your-data-provider" )
{
	YourParser->parseContent();
#	print "Got other-data\n";
}
elsif ( defined $ARGV[0] )
{
#	my $FILE="/tmp/rates$ARGV[0]";
	my $DESTINATION_NAME="$ARGV[0]";
	my $line;

#	print $FILE,"\n";
#	print $DESTINATION_NAME,"\n";

	my $URL="http://pda.teltarif.de/db/res-pda.html?ziel=$DESTINATION_NAME&zs=heute&zs=jetzt";
	my $GET="lynx -nolist -dump ";
	open (F, "$GET \"$URL\" |");
	my @output = <F>;
	my $found = 0;
	foreach $line (@output)
	{
	  if ($line =~ /Platz/ ) {
	    $found = 1;
	  } 
	  elsif ($found >= 1 && $found <= 5) {
	    $line =~ s/^ *[0-9] *//;              # remove "Platz"
            $line =~ s/^([0-9]+) +/$1\n/;         # insert new-line after "Zugang"
	    $line =~ s/Cent +/Cent\n/;            # insert new-line after "Minutenpreis"
	    $line =~ s/([0-9]+\/[0-9]+) .*/$1/; # insert new-line after "Takt"	    
	    print $line;
	    $found++;
	  }
	}
}
