package GCPlugins::GCmusics::GCDiscogs;

###################################################
#
#  Copyright 2005-2007 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::GCmusics::GCmusicsCommon;

{
    package GCPlugins::GCmusics::GCPluginDiscogs;

    use base 'GCPlugins::GCmusics::GCmusicsPluginsBase';
    use XML::Simple;

    sub parse
    {
        my ($self, $page) = @_;
        my $xml;
        my $xs = XML::Simple->new;
        if ($self->{parsingList})
        {
            $xml = $xs->XMLin($page,
                              ForceArray => ['result', 'event'],
                              KeyAttr => {'release' => ''});
            my $release;
            foreach $release ( @{ $xml->{'searchresults'}->{result} } )
            {
                if ($release->{type} eq 'release')
                {
                   $self->{itemIdx}++;
                   $self->{itemsList}[$self->{itemIdx}]->{url} = $release->{uri};
                   my $found = index($release->{title},"-");
                   if ( $found >= 0 )
                   {
                      $self->{itemsList}[$self->{itemIdx}]->{title} = substr($release->{title}, $found +length('-'),length($release->{title})- $found -length('-'));
                      # Enleve les blancs en debut de chaine
                      $self->{itemsList}[$self->{itemIdx}]->{title} =~ s/^\s+//;

                      $self->{itemsList}[$self->{itemIdx}]->{artist} = substr($release->{title}, 0, $found);
                      # Enleve les blancs en fin de chaine
                      $self->{itemsList}[$self->{itemIdx}]->{artist} =~ s/\s+$//;
                   }
                   else
                   {
                      $self->{itemsList}[$self->{itemIdx}]->{title} = $release->{title};
                   }
                }
            }
        }
        else
        {
            $xml = $xs->XMLin($page,
                              ForceArray => ['track', 'artist', 'image', 'label', 'genre'],
                              KeyAttr => {'track' => ''});
            $self->{curInfo}->{title} = $xml->{release}->{title};
            $self->{curInfo}->{artist} = '';
            for my $art (@{$xml->{release}->{artists}->{artist}})
            {
                $self->{curInfo}->{artist} .= $art->{name}.', ';
            }
            $self->{curInfo}->{artist} =~ s/, $//;
            $self->{curInfo}->{producer} = '';
            $self->{curInfo}->{composer} = '';
            for my $rel (@{$xml->{release}->{extraartists}->{artist}})
            {
                $self->{curInfo}->{producer} .= $rel->{name}.', '
                    if $rel->{role} eq 'Producer';
                $self->{curInfo}->{composer} .= $rel->{name}.', '
                    if (($rel->{role} eq 'Composed By') || ($rel->{role} eq 'Score') || ($rel->{role} eq 'Songwriter') || ($rel->{role} eq 'Written-By'));
            }
            $self->{curInfo}->{producer} =~ s/, $//;
            $self->{curInfo}->{composer} =~ s/, $//;
            $self->{curInfo}->{release} = $xml->{release}->{released};
            for my $track(@{$xml->{release}->{'tracklist'}->{track}})
            {
                my $duree = $track->{duration};
                $duree =~ /([0-9]+):([0-9]+)/;
                my $duree2 = int($1*60 + $2) ;
                $self->addTrack($track->{title}, $duree2, $track->{position});
            }
            $self->{curInfo}->{tracks} = $self->getTracks;
            $self->{curInfo}->{running} = $self->getTotalTime;
            for my $cover(@{$xml->{release}->{images}->{image}})
            {
               $self->{curInfo}->{cover} = $cover->{uri} if $self->{curInfo}->{cover} eq '';
            }
            $self->{curInfo}->{label} = '';
            for my $label (@{$xml->{release}->{labels}->{label}})
            {
                $self->{curInfo}->{label} .= $label->{name}.', ';
            }
            $self->{curInfo}->{label} =~ s/, $//;
            $self->{curInfo}->{genre} = '';
            for my $genre (@{$xml->{release}->{genres}->{genre}})
            {
                $self->{curInfo}->{genre} .= $genre.',';
            }
            $self->{curInfo}->{genre} =~ s/,$//;
        }
    }

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

        $self->{hasField} = {
            title => 1,
            artist => 1,
            release => 0
        };

        return $self;
    }

    sub preProcess
    {
        my ($self, $html) = @_;

     return $html;
    }
    
    sub decodeEntitiesWanted
    {
        return 0;
    }

    sub getSearchUrl
    {
		my ($self, $word) = @_;
	
        return "http://www.discogs.com/search?type=all&q=". $word ."&f=xml&api_key=e8f5ae8ba2";
    }
    
    sub getItemUrl
    {
		my ($self, $url) = @_;

        my $found = index(reverse($url),"/");
        if ( $found >= 0 )
        {
           my $id = substr(reverse($url), 0, $found);
           $url = "http://www.discogs.com/release/". reverse($id) ."?f=xml&api_key=e8f5ae8ba2";
        }
        return $url;
    }

    sub changeUrl
    {
        my ($self, $url) = @_;
        
        return $url;
    }

    sub getName
    {
        return 'Discogs';
    }
    
    sub getAuthor
    {
        return 'TPF';
    }
    
    sub getLang
    {
        return 'EN';
    }

    sub getCharset
    {
        my $self = shift;
    
        return "UTF-8";
    }

    sub convertCharset
    {
        my ($self, $value) = @_;
        return $value;
    }

    sub getNotConverted
    {
        my $self = shift;
        return [];
    }

    sub getSearchFieldsArray
    {
        return ['title'];
    }
}

1;
