package GCPlugins::GCcomics::GCbedetheque;

###################################################
#
#  Copyright 2005-2009 Tian
#
#  This file is part of GCstar.
#
#  GCstar is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  GCstar 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 General Public License
#  along with GCstar; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###################################################

use strict;
use utf8;

use GCPlugins::GCcomics::GCcomicsCommon;

{

	package GCPlugins::GCcomics::GCPluginbedetheque;

	use LWP::Simple qw($ua);

	use base qw(GCPlugins::GCcomics::GCcomicsPluginsBase);

	sub start
	{

		#print ".";
		my ( $self, $tagname, $attr, $attrseq, $origtext ) = @_;
		if ( $self->{parsingList} )
		{

#The interesting part to parse looks like this :
#<A HREF="serie-11736-BD-Ratafia.html#47448" Title="Ratafia"><i><font color=#44aaff>Ratafia</font></i></A>  -1-  Mon nom est Capitaine</TD><TD align="left">
			if ( ( $tagname eq "a" ) && ( $attr->{href} =~ m/serie-/ ) )
			{
				$self->{isCollection} = 1;
				$self->{itemIdx}++;
				
				my $searchUrl =  substr($attr->{href},0,index($attr->{href},"."))."__10000".substr($attr->{href},index($attr->{href},"."));
                		$self->{itemsList}[$self->{itemIdx}]->{url} = $searchUrl;

				#$self->{itemsList}[ $self->{itemIdx} ]->{url} =
				#  "http://www.bedetheque.com/" . $attr->{href};
				$self->{itemsList}[ $self->{itemIdx} ]->{series} =
				  $attr->{title};
			}
		}
		else
		{

#The interesting part to parse looks like this :
#<a name="47448">. Mon nom est Capitaine</a>
#<td width="90">Identifiant :</td><td>47448</td>
#<td>Scénario :</td><td>
#<td>Dessin :</td>Salsedo, Frédéric
#<td>Couleurs :</td><td>Salsedo, Greg
#<td>Dépot légal :</td><td>06/2005</td>
#<td>Achevé impr. :</td><td>05/2005</td>
#<td>Estimation :</td><td>non coté</td>
#<td>Editeur :</td><td>Milan</td>
#<td>Collection :</td><td>[Treize Etrange]</td>
#<td>Taille :</td><td>Format normal</td>
#<td>ISBN :</td><td>2-7459-1664-5</td>
#<td>Autres info :</td><td>&nbsp;<IMG SRC="images/Edo.png" BORDER=0 alt="Edition originale" TITLE="Edition originale"></td>
#<td>Planches :</td><td>46</td>
			if ( $attr->{name} eq $self->{site_internal_id} )
			{
				$self->{isIssue} = 1;
				$self->{itemIdx}++;
			}
			if (   ( $tagname eq "a" )
				&& ( $attr->{href} =~ m/Couvertures.*\.[jJ][pP][gG]/ ) )
			{
				$self->{last_cover} =
				  'http://www.bedetheque.com/' . $attr->{href};
			}
		}
	}

	sub end
	{
		my ( $self, $tagname ) = @_;
		if ( $self->{parsingList} )
		{
			if ( ( $tagname eq "a" ) && $self->{isCollection} == 1 )
			{

				#end of collection, next field is title
				$self->{isTitle}      = 1;
				$self->{isCollection} = 0;
			}
		}
		else
		{
			if ( ( $tagname eq "table" ) && $self->{isResultsTable} == 1 )
			{
				$self->{isResultsTable} = 0;
				$self->{parsingEnded}   = 1;
			}
		}
	}

	sub text
	{
		my ( $self, $origtext ) = @_;

		return if ( $origtext eq " " );

		return if ( $self->{parsingEnded} );

		if ( $self->{parsingList} )
		{
			if ( $self->{isTitle} )
			{

				#sometimes the field is "-vol-title", sometimes "--vol-title"
				$origtext =~ s/-+/-/;
				my @fields = split( /-/, $origtext );
				#print $origtext . "|" . @fields . "\n";
				$self->{itemsList}[ $self->{itemIdx} ]->{volume} = $fields[1];
				$self->{itemsList}[ $self->{itemIdx} ]->{title}  = $fields[2];
				$self->{isTitle}                                 = 0;
			}
		}
		else
		{
			$self->{curInfo}->{series}   = $self->{serie};
			$self->{curInfo}->{synopsis} = $self->{synopsis};

			if ( $self->{isResultsTable} == 1 )
			{
				$self->{curInfo}->{image} = $self->{last_cover};

				my %td_fields_map = (
					"Identifiant :"   => '',
					"Scénario :"     => 'writer',
					"Dessin :"        => 'illustrator',
					"Couleurs :"      => 'colourist',
					"Dépot légal :" => 'publishdate',
					"Achevé impr. :" => 'printdate ',
					"Estimation :"    => 'cost',
					"Editeur :"       => 'publisher',
					"Collection : "   => 'collection',
					"Taille :"        => 'format',
					"ISBN :"          => 'isbn',
					"Planches :"      => 'numberboards'
				);

				if ( exists $td_fields_map{$origtext} )
				{
					$self->{current_field} = $td_fields_map{$origtext};
					#print "Field => $origtext ";
				}
				else
				{
					$self->{curInfo}->{$self->{current_field}} = $origtext;
					$self->{current_field} = "";
					#print "Value => $origtext \n";
				}
			}
			if ( $self->{isTitle} )
			{
				$origtext =~ s/^.\s//;    #remove ". " in front of title.
				$self->{curInfo}->{title} = $origtext;
				$self->{isTitle} = 0;
			}
			if ( $self->{isIssue} )
			{

				if ( !( $origtext =~ m/^\d+$/ ) )
				{

		#for one-shots there is no volume field and the first field is the title
					$self->{curInfo}->{title} = $origtext;
					$self->{isIssue}           = 0;
					$self->{isResultsTable}    = 1;
				}
				else
				{
					$self->{curInfo}->{volume} = $origtext;
					$self->{isIssue}           = 0;
					$self->{isTitle}           = 1;
					$self->{isResultsTable}    = 1;
				}
			}
		}
	}

	sub new
	{
		#print "new";
		my $proto = shift;
		my $class = ref($proto) || $proto;
		my $self  = $class->SUPER::new();
		bless( $self, $class );

		$self->{hasField} = {
			series => 1,
			title  => 1,
			volume => 1,
		};

		$self->{isResultsTable}   = 0;
		$self->{itemIdx}          = 0;
		$self->{last_cover}       = "";
		$self->{site_internal_id} = "";
		$self->{serie}            = "";
		$self->{synopsis}         = "";
		$self->{current_field}    = "";

		return $self;
	}

	sub preProcess
	{
		my ( $self, $html ) = @_;
		#print "prepro\n";

		if ( $self->{parsingList} )
		{

			#keep only albums, no series or objects
			$html =~ m/(<b>\d+\salbum.*?trouv.*?)\n/;
			$html = $1;
			#print $html;
		}
		else
		{

#easier to get serie title and synopsis here with regexp than in the html parsing
			$html =~ m/<h1>(.*?)<\/h1>/;
			$self->{serie} = $1;
			$html =~ m/Note moyenne(.*?\n)*?.*?BR>((.*?))</;
			$self->{synopsis} = $2;
		}

		return $html;
	}

	sub getSearchUrl
	{
		my ( $self, $word ) = @_;
		if ($self->{searchField} eq 'series')
		{
		    return "http://www.bedetheque.com/index.php?R=1&RechSerie=$word";
		}
		elsif ($self->{searchField} eq 'writer')
		{
		    return "http://www.bedetheque.com/index.php?R=1&RechAuteur=$word";
		}
		else
		{
		    return '';
		}
		#return "http://www.bedetheque.com/index.php?R=1&RechTexte=$word";
	}

    sub getSearchFieldsArray
    {
        return ['series', 'writer'];
    }

	sub getItemUrl
	{
		my ( $self, $url ) = @_;
		#print "getitemurl " . $url . "\n";
		my @array = split( /#/, $url );
		$self->{site_internal_id} = $array[1];

		return $url if $url =~ /^http:/;
		return "http://www.bedetheque.com/" . $url;
	}

	sub getNumberPasses
	{
		return 1;
	}

	sub getName
	{
		return "Bedetheque";
	}

	sub getAuthor
	{
		return 'Chessnico';
	}

	sub getLang
	{
		return 'FR';
	}
}
