package GCImport::GCImportTellico;

###################################################
#
#  Copyright 2005 Tian
#
#  This file is part of GCfilms.
#
#  GCfilms 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.
#
#  GCfilms 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 GCfilms; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###################################################

use strict;
use GCImport::GCImportBase;

{
    package GCImport::GCImporterTellico;

    use base qw(GCImport::GCImportBaseClass);
    use File::Spec;
    
    eval "use XML::Simple"; my $hasXmlSimple = $@ ? 0 : 1;    
    eval "use Archive::Zip"; my $hasZip = $@ ? 0 : 1;
    eval "use MIME::Base64"; my $hasBase64 = $@ ? 0 : 1;

    sub new
    {
        my $proto = shift;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new();
        bless ($self, $class);
        
        $self->{errors} = '';
        $self->{errors} .= "XML::Simple\n" if (!$hasXmlSimple);
        $self->{errors} .= "Archive::Zip\n" if (!$hasZip);
        $self->{errors} .= "Mime::Base64\n" if (!$hasBase64);

        return $self;
    }

    sub getName
    {
        return "Tellico (.tc)";
    }
    
    sub getOptions
    {
        my $self = shift;
        my @options;
        return \@options;
    }
    
    sub getFilePatterns
    {
        my $self = shift;
    
        return (['Tellico Format (.tc)', '*.tc'], ['Tellico XML (.xml)', '*.xml']);
    }
    
    sub wantsFieldsSelection
    {
        return 0;
    }
    sub getEndInfo
    {
        my $self = shift;
    
        return $self->{parsingError};
    }
    
    sub getMoviesArray
    {
        my ($self, $file) = @_;

        my @result;
    	
    	my $type;
    	my $xml;
    	my $zip;
    	
    	# File type is based on suffix
    	# T is for Tellico (zipped file)
    	# X is for XML
    	$type = ($file =~ m/tc$/) ? 'T' : 'X';
    	
        #First we uncompress file
        if ($type eq 'T')
        {
            $zip = Archive::Zip->new($file);
            $xml = $zip->contents('tellico.xml');
        }
        else
        {
            open XML, $file;
            $xml = do {local $/; <XML>};
            close XML;
        }
	
	    #Then we parse XML data
        my $xs = XML::Simple->new;
        my $tellico = $xs->XMLin($xml);
        my $collection = $tellico->{collection};
	
	    #We check it is a movie collection
	    if ($collection->{type} != 3)
	    {
            $self->{parsingError} = $self->{options}->{lang}->{ImportTellicoNotVideo};
            return \@result;
	    }
	    
        my %tmpMap;
        # If there are no ids, we have an array in $collection
        if (ref ($collection->{entry}) eq 'ARRAY')
        {
            my $i = 0;
            #Then we prepare a map
            foreach (@{$collection->{entry}})
            {
                $tmpMap{$i} = $_;
                $i++;
            }
        }
        else
        {
            %tmpMap = %{$collection->{entry}};
        }

	    #Loop on entries
	    my $i = 0;
	    while (my ($id, $entry) = each (%tmpMap))
	    {
            $result[$i]->{title} = $entry->{title} if ref($entry->{title}) ne 'HASH';
            $result[$i]->{format} = $entry->{medium} if ref($entry->{medium}) ne 'HASH';
            $result[$i]->{date} = $entry->{year} if ref($entry->{year}) ne 'HASH';

            my $certification = $entry->{certification};
            if ($certification eq 'U (USA)')
            {
                $result[$i]->{age} = 1;
            }
            elsif ($certification eq 'G (USA)')
            {
                $result[$i]->{age} = 2;
            }
            elsif ($certification eq 'PG (USA)')
            {
                $result[$i]->{age} = 5;
            }
            elsif ($certification eq 'PG-13 (USA)')
            {
                $result[$i]->{age} = 13;
            }
            elsif ($certification eq 'R (USA)')
            {
                $result[$i]->{age} = 17;
            }

            if (ref ($entry->{genres}->{genre}) eq 'ARRAY')
            {
                for my $genre(@{$entry->{genres}->{genre}})
                {
                    $result[$i]->{type} .= $genre.',';
                }
                $result[$i]->{type} =~ s/,$//;
            }
            else
            {
                $result[$i]->{type} = $entry->{genres}->{genre};
            }

            if (ref ($entry->{nationalitys}->{nationality}) eq 'ARRAY')
            {
                for my $nat(@{$entry->{nationalitys}->{nationality}})
                {
                    $result[$i]->{nat} .= $nat.', ';
                }
                $result[$i]->{nat} =~ s/, $//;
            }
            else
            {
                $result[$i]->{nat} = $entry->{nationalitys}->{nationality};
            }

            $result[$i]->{video} = $entry->{format} if ref($entry->{format}) ne 'HASH';

            if (ref ($entry->{casts}->{cast}) eq 'ARRAY')
            {
                for my $cast(@{$entry->{casts}->{cast}})
                {
                    if (ref ($cast->{column}) eq 'ARRAY')
                    {
                        $result[$i]->{actors} .= $cast->{column}->[0].' ('.$cast->{column}->[1].'), ';
                    }
                    else
                    {
                         $result[$i]->{actors} .= $cast->{column}.', ';
                    }
                }
                $result[$i]->{actors} =~ s/, $//;
            }
            else
            {
                $result[$i]->{actors} = $entry->{casts}->{cast};
            }

            if (ref ($entry->{directors}->{director}) eq 'ARRAY')
            {
                for my $director(@{$entry->{directors}->{director}})
                {
                    $result[$i]->{director} .= $director.', ';
                }
                $result[$i]->{director} =~ s/, $//;
            }
            else
            {
                $result[$i]->{director} = $entry->{directors}->{director};
            }
            
            if (ref ($entry->{languages}->{language}) eq 'ARRAY')
            {
                for my $language(@{$entry->{languages}->{language}})
                {
                    $result[$i]->{audio} .= $language.',';
                }
                $result[$i]->{audio} =~ s/,$//;
            }
            else
            {
                $result[$i]->{audio} = $entry->{languages}->{language};
            }
            if (ref ($entry->{subtitles}->{subtitle}) eq 'ARRAY')
            {
                for my $subtitle(@{$entry->{subtitles}->{subtitle}})
                {
                    $result[$i]->{subt} .= $subtitle.',';
                }
                $result[$i]->{subt} =~ s/,$//;
            }
            else
            {
                $result[$i]->{subt} = $entry->{subtitles}->{subtitle};
            }

            $result[$i]->{time} = $entry->{'running-time'} if ref($entry->{'running-time'}) ne 'HASH';
            $result[$i]->{synopsis} = $entry->{plot} if ref($entry->{plot}) ne 'HASH';

            my $rating = $entry->{rating};
            if ($rating =~ /^5/)
            {
                $result[$i]->{rating} = 10;
            }
            elsif ($rating =~ /^4/)
            {
                $result[$i]->{rating} = 7;
            }
            elsif ($rating =~ /^2/)
            {
                $result[$i]->{rating} = 3;
            }
            elsif ($rating =~ /^1/)
            {
                $result[$i]->{rating} = 0;
            }
            else #if ($rating =~ /^3/) || ($rating == undef)
            {
                $result[$i]->{rating} = 5;
            }

            #$result[$i]->{borrower} = 'none' if (! $entry->{loaned});
            $result[$i]->{borrower} = 'Unknown' if ($entry->{loaned} eq 'true');
            $result[$i]->{comment} = $entry->{comments} if ref($entry->{comments}) ne 'HASH';

            #Picture management
            my $imageId = $entry->{cover};
            if ($imageId && ref($imageId) ne 'HASH')
            {
                (my $suffix = $imageId) =~ s/.*?(\.[^.]*)$/$1/;
                my $fileName = $self->{options}->{parent}->getUniqueImageFileName($suffix);
                if ((exists $collection->{images}->{image}->{$imageId}) &&
                    (exists $collection->{images}->{image}->{$imageId}->{content}))
                {
                    # Picture is embedded
                    my $data = MIME::Base64::decode_base64($collection->{images}->{image}->{$imageId}->{content});
                    open PIC, ">$fileName";
                    print PIC $data;
                    close PIC;
                }
                else
                {
                    if ($type eq 'T')
                    {
                        # Only zipped file may have external pictures
                        my $picName = 'images/'.$imageId;
                        $zip->extractMember($picName, $fileName);
                    }
                    else
                    {
                        $fileName = '';
                    }
                }
                $result[$i]->{image} = $self->{options}->{parent}->transformPicturePath($fileName);
            }

	        $i++;
	    }
	    
        return \@result;

	}
}

1;