#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Dashboard::Module::BookSummary;

use strict;
use warnings;

use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::PeriodMonth;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Client;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::AggMProductSales;
use BookPub::Analytics::BooksSummaryReport;
use BookPub::DB::Item::BookProductImageFile;
use BookPub::DB::Item::BookProduct;

use lib '/app/tools/mediaserve/lib';
use MediaServe::Image::ImageFile;

use constant kDefaultCoverArtThumbnail => "/production/images/no_book_cover_thumbnail.png";

use Common::FormObject;
use base 'Common::LandingPage::Module';

sub DisplayOrder { 7 }
sub Stylesheet   { "/app/tools/bookpub/templates/dashboard/module/book_summary.xsl" }
sub Template     { "dashboardBookSummary" }
sub Title        { "Top Books" }
sub Class        { "bodyModule" }

sub relatedCommands {
    qw(
      bookpub/analytics/b
      bookpub/analytics/bs
    );
}

sub _init {
    my $self = shift;
    my %args = @_;

    my $timeframe = $args{timeframe};

    if ( $timeframe && $timeframe eq 'ytd' ) {
        $self->{_yearToDate} = 1;
    } elsif ( $timeframe && $timeframe =~ /^\d+$/ ) {
        $self->{_months} = $timeframe;
    } else {
        $self->{_months} = 3;
    }

    return $self->SUPER::_init(@_);
}

sub _initProperties {
    my $self = shift;

    my @periods = $self->_getPeriods();

    $self->{TopBooks}->{Book} = $self->_getTopAlbums(@periods);

    return $self->SUPER::_initProperties(@_);
}

sub _getPeriods {
    my $self       = shift;
    my $collection = Raptor::DB::Item::PeriodMonth->GetLatestByRange(
        months => $self->{_months},
        ytd    => $self->{_yearToDate}
    );
    my @result;

    while ( my $period = $collection->next() ) {
        push( @result, $period->month_id );
    }

    return @result;
}

sub _getTopAlbums {
    my $self    = shift;
    my @periods = @_;
    my $rank    = 1;

    return unless (@periods);

    my @books;

    my $collection = BookPub::DB::Item::AggMProductSales->GetTopBooksByPeriods( limit => 5, periods => \@periods );

    while ( my $book = $collection->next() ) {
        my $result = {
            Rank        => $rank,
            CountryCode => $book->country_code,
            ServiceID   => $book->service_id,
            Units       => Common::Client::Current()->Locale()->formatNumber( $book->units ),
            Revenue     => Common::Client::Current()->Locale()->formatMoney( Common::RSMath::round( $book->revenue, 2 ) ),
            Product     => BookPub::Analytics::BooksSummaryReport->_getBookInfo( product_id => $book->product_id ),
            Thumbnail   => $self->_getCoverArt( $book->product_id ),
        };
        push( @books, $result );

        $rank++;
    }

    return \@books;
}

sub _getCoverArt {
    my $self = shift;
    my $product_id = shift || die "product id required";
    my $url;

    # First look for artwork for this product.
    $url = $self->_lookupCoverArt($product_id);

    # If not found then try to find artwork for any of the products with the same book id
    unless ($url) {
        foreach my $product ( $self->_getAlternateProducts($product_id) ) {
            $url = $self->_lookupCoverArt($product);

            last if ($url);
        }
    }

    $url = kDefaultCoverArtThumbnail unless ($url);
    return $url;
}

sub _getAlternateProducts {
    my $self = shift;
    my $product_id = shift || return ();
    my @products;

    my $product = BookPub::DB::Item::BookProduct->Lookup( product_id => $product_id );
    my $collection = BookPub::DB::Item::BookProduct->GetAllByBookID( $product->book_id );

    while ( my $otherProduct = $collection->next() ) {
        push( @products, $otherProduct->product_id );
    }

    return @products;
}

sub _lookupCoverArt {
    my $self = shift;
    my $product_id = shift || return;
    my $url;

    my $thumbFile = BookPub::DB::Item::BookProductImageFile->Lookup(
        book_product_id => $product_id,
        file_type       => 'thumbnail',
    );

    if ($thumbFile) {
        Common::Log::Print("FOUND THUMBNAIL");
        my $image = MediaServe::Image::ImageFile->new( clientID => Common::RSApp::GetClientID(), id => $thumbFile->media_file_id );
        if ($image) {
            $url = $image->url();
        }
    } else {
        my $origFile = BookPub::DB::Item::BookProductImageFile->Lookup(
            book_product_id => $product_id,
            file_type       => 'original',
        );

        if ($origFile) {
            Common::Log::Print("DEFAULTING TO ORIGINAL");
            my $image = MediaServe::Image::ImageFile->new( clientID => Common::RSApp::GetClientID(), id => $origFile->media_file_id );
            if ($image) {
                $url = $image->url();
            }
        }
    }

    return $url;
}

###
1;    #
###
