package BookPub::RDAS::Parser::BestSellerList::NewYorkTimes;

use strict;
use warnings;
use Data::Dumper;
use Common::Date;
use Encode;

use utf8;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::BestSellerMonitor;
use BookPub::DB::Item::BestSellerBook;
use BookPub::DB::Item::BestSellerList;

use base 'BookPub::RDAS::Parser::BestSellerList';

sub parse {
    my $self = shift;
    my $book;
    my $isbnSet;
    my $listID;
    my @bookResults;

    my $content = $self->content();
    Common::Assert::assert($content);
    my $encoded = Encode::encode_utf8($content);

    $self->{_parser} = XML::Simple->new();
    my $ref = $self->{_parser}->XMLin($encoded);

    my $datePosted = Common::Date->new( $ref->{last_modified} );

    foreach $book ( @{ $ref->{results}->{book} } ) {

        $listID = BookPub::DB::Item::BestSellerList->GetListIDByName( $book->{list_name} );

        # if there was only 1 element in the isbns array, perl errors
        # out with "Not an ARRAY".  Here we make the reference into a scalar
        # if it's not an array
        my $isbnref = $book->{isbns}{isbn};
        $isbnref = [$isbnref] unless 'ARRAY' eq ref($isbnref);

        # with possible multiple isbns associated with a single book title,
        # we need to loop through the isbnSet
        foreach $isbnSet (@$isbnref) {
            push @bookResults,
              {
                date_posted         => $datePosted->asString,
                best_seller_list_id => $listID,
                title               => $book->{book_details}->{book_detail}->{title},
                author              => $book->{book_details}->{book_detail}->{author},
                imprint             => $book->{book_details}->{book_detail}->{publisher},
                rank                => $book->{rank},
                isbn10              => $book->{book_details}->{book_detail}->{primary_isbn10},
                isbn13              => $book->{book_details}->{book_detail}->{primary_isbn13},
                related_isbn10      => $isbnSet->{isbn10},
                related_isbn13      => $isbnSet->{isbn13},
              };
        }
    }

    $self->{_book_results} = \@bookResults;
    return $self->{_book_results};

}

sub BookResults { shift->{_book_results} }

1;
