#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Analytics::ImprintsSummaryReport;
use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use Common::Assert;
use Common::XMLObject;
use Common::RSApp;
use Common::Client;

use lib '/app/tools/data_classes/lib';
use Period::QuarterPeriod;
use Period::MonthPeriod;
use Period::YearPeriod;

use lib '/app/tools/bookpub/lib';
use BookPub::Analytics::ReportLib;    # for pie charts
use BookPub::Stats::Sales;
use base 'BookPub::Analytics::BaseReport';

sub _init {
    my ( $self, %args ) = @_;

    $self->SUPER::_init(%args);

    my $stats_obj = $self->{_stats};
    return $self unless ($stats_obj);

    # --------------------------
    # grand total data
    # --------------------------
    my $total_metric = {};
    $total_metric              = $stats_obj->GetTotalMetric( %{ $self->{_statParams} } );
    $self->{Totals}->{Revenue} = Common::Client::Current()->Locale()->formatMoney( $total_metric->Revenue );
    $self->{Totals}->{Units}   = Common::Client::Current()->Locale()->formatNumber( $total_metric->Units );

    # --------------------------
    # build the pie and table data at the same time
    # --------------------------
    my $pie_count      = 0;
    my $base_image_url = '';
    my $pie_data       = {};
    my $table_data     = [];
    my $data_labels    = [];

    my $imprint_info  = $self->_getImprintMap();
    my $imprints      = $stats_obj->GetTopRanking( category => 'imprint' );
    my $imprints_prev = $stats_obj->GetTopRanking( category => 'imprint', prev_rank => 1 );
    my $top_services  = $stats_obj->GetTopRanking( category => 'service', ignore => 'imprint', limit => 5 );
    my $service_names = $self->_getServiceMap();
    my @metric_list   = map { $_->ID } @$top_services;
    my $total_revenue = $args{imprintID} ? BookPub::Analytics::BaseReport::_sumRevenue($imprints) : $total_metric->Revenue;

    my $c             = 1;
    my $other_revenue = 0;
    my %seen          = ();

    # If a publisher id was passed in, we want to restrict the list to just the imprints for that publisher.
    #
    my $allowedPublisherImprints = {};
    my $publisher_param          = $args{publisherID};
    my $publisherImprints        = BookPub::DB::Item::PublisherImprints->GetAllSortedByName();
    while ( $publisherImprints->hasNext() ) {
        my $pi = $publisherImprints->next();

        if ( $publisher_param and $publisher_param eq $pi->publisher_id ) {
            $allowedPublisherImprints->{ $pi->imprint_id } = 1;
        }
    }

    #die Dumper $allowedPublisherImprints;

    foreach my $imprint_ref (@$imprints) {
        my $imprint_id = $imprint_ref->ID;

        # Here's where we omit the imprints that are not related to the specified publisher.
        #
        if ( $publisher_param && !$allowedPublisherImprints->{$imprint_id} ) {
            $seen{$imprint_id} = 1;
            next;
        }

        if ( $c++ <= 10 and ( $total_revenue and $imprint_ref->Revenue / $total_revenue ) >= 0.01 ) {
            next if ( $imprint_ref->Revenue <= 0 );

            push @{ $pie_data->{labels} }, $imprint_info->{$imprint_id};
            push @{ $pie_data->{ids} },    $imprint_id;
            push @{ $pie_data->{data} },   $imprint_ref->Revenue;
        } else {
            $other_revenue += $imprint_ref->Revenue;
        }

        my $row_data = {
            Rank     => $imprint_ref->Rank,
            Units    => Common::Client::Current()->Locale()->formatNumber( $imprint_ref->Units ),
            Revenue  => Common::Client::Current()->Locale()->formatMoney( $imprint_ref->Revenue ),
            PrevRank => $imprints_prev->{$imprint_id},
        };

        $row_data->{ProductInfo}->{ImprintName} = $imprint_info->{$imprint_id};
        $row_data->{ProductInfo}->{ImprintID}   = $imprint_id;
        $seen{$imprint_id}                      = 1;

        my @extra_data     = ();
        my $summary_metric = $stats_obj->GetSummaryMetric(
            category    => 'service',
            metric_list => \@metric_list,
            imprint_id  => $imprint_id,
        );

        foreach my $service_ref (@$top_services) {
            push @extra_data, Common::Client::Current()->Locale()->formatMoney( $summary_metric->{ $service_ref->ID } || 0 );
            push @$data_labels, $service_names->{ $service_ref->ID };
        }
        $row_data->{Data} = \@extra_data;

        push @$table_data, $row_data;
    }

    # add any imprints not yet seen above
    foreach my $imprint_id ( sort { lc( $imprint_info->{$a} ) cmp lc( $imprint_info->{$b} ) } keys %$imprint_info ) {

        if ( $publisher_param && !$allowedPublisherImprints->{$imprint_id} ) {
            next;
        }

        next if ( $seen{$imprint_id} );
        my @place_holders = ();
        map { push @place_holders, 0 } @$top_services;
        push @$table_data,
          {
            Units       => 0,
            Revenue     => 0,
            Rank        => '--',
            PrevRank    => '--',
            ProductInfo => {
                ImprintName => $imprint_info->{$imprint_id},
                ImprintID   => $imprint_id
            },
            Data => \@place_holders,
          };
    }

    my $xml_href = {};

    if ( $pie_data && defined $pie_data->{data} ) {
        if ($other_revenue) {
            push @{ $pie_data->{labels} }, 'Other';
            push @{ $pie_data->{data} },   $other_revenue;
        }

        my $image_link = $args{commandObj}->getParamsAsString( c => 1, imprint => 1 );
        $image_link .= '&' if ( length $image_link );
        $image_link .= 'c=m&imprint=';

        #        my $q = $self->GetPartialQueryString(view => 1, label => 1);
        #        substr($q,0,0) = '&' if $q;
        #        my $image_link = "view=m$q&label=";
        my $pie_href = GetPieChart(
            labels         => $pie_data->{labels},
            data           => $pie_data->{data},
            image_map_link => $image_link,
            label_ids      => $pie_data->{ids},
        );
        $xml_href->{PieName}        = 'imprint_revenue';
        $xml_href->{ImageSrc}       = $pie_href->{image_src};
        $xml_href->{ImageMap}       = $pie_href->{image_map};
        $xml_href->{Legend}->{Item} = $pie_href->{legend_xml};
    }

    my @tables = ();

    if ( $table_data && ( scalar @$table_data >= 1 ) ) {
        my $table_href = CreateTableXML( data => $table_data, labels => $data_labels );

        if ($table_href) {
            $table_href->{TableName} = 'top_imprints';
            push @tables, $table_href;
        }
    }

    $self->{Pies}->{Pie} = [$xml_href] if ( keys %$xml_href );
    $self->{Tables}->{Table} = \@tables;

    return $self;
}

sub _initStatsParams {
    my ( $self, %args ) = @_;
    my $offset = $self->_getPageOffset( $args{pageNum} );

    # This hash of parameters gets re-used several times.
    # !!! Why, I don't really understand.  That needs to be fixed.
    #
    my %params = (
        period_id    => $self->{_period}->PeriodID,
        period_type  => $self->{_period}->PeriodType,
        end_period_id => $args{endPeriodParam},
        client_id    => Common::RSApp::GetClientID(),
        imprint_id   => $args{imprintID},
        publisher_id => $args{publisherID},
        country_code => $args{countryCode},

        #product_type => $args{productType},
        offset  => $offset,
        user_id => $args{commandObj}->_getUser()->UserID(),
    );

    return \%params;
}

1;
