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

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 BookPub::Analytics::BaseReport;
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 $geo_map = BookPub::Analytics::BaseReport::_mapCountries( $stats_obj->GetCountryList( all => 1 ) );
    my $geo          = $stats_obj->GetTopRanking( category => 'country' );
    my $geo_prev     = $stats_obj->GetTopRanking( category => 'country', prev_rank => 1 );
    my $top_services = $stats_obj->GetTopRanking( category => 'service', ignore => 'country', limit => 5 );
    my $service_names = $self->_getServiceMap();
    my @metric_list   = map { $_->ID } @$top_services;
    my $total_revenue = $args{countryCode} ? BookPub::Analytics::BaseReport::_sumRevenue($geo) : $total_metric->Revenue;

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

    foreach my $geo_ref (@$geo) {
        my $c_code = $geo_ref->ID;

        if ( $c++ <= 10 and ( $total_revenue > 0 and $geo_ref->Revenue / $total_revenue ) >= 0.01 ) {
            push @{ $pie_data->{labels} }, $geo_map->{$c_code};
            push @{ $pie_data->{ids} },    $c_code;
            push @{ $pie_data->{data} },   $geo_ref->Revenue;
        } else {
            $other_revenue += $geo_ref->Revenue;
        }

        my $row_data = {
            Rank     => $geo_ref->Rank,
            Units    => Common::Client::Current()->Locale()->formatNumber( $geo_ref->Units ),
            Revenue  => Common::Client::Current()->Locale()->formatMoney( $geo_ref->Revenue ),
            PrevRank => $geo_prev->{$c_code},
        };

        $row_data->{ProductInfo}->{CountryName} = $geo_map->{$c_code};
        $row_data->{ProductInfo}->{CountryID}   = $c_code;
        $seen{$c_code}                          = 1;

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

        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 countries not yet seen above
    foreach my $ccode ( sort { $geo_map->{$a} cmp $geo_map->{$b} } keys %$geo_map ) {
        next if ( $seen{$ccode} or $ccode eq '??' );
        my @place_holders = ();
        map { push @place_holders, 0 } @$top_services;
        push @$table_data,
          {
            Units       => 0,
            Revenue     => 0,
            Rank        => '--',
            PrevRank    => '--',
            ProductInfo => {
                CountryName => $geo_map->{$ccode},
                CountryID   => $ccode
            },
            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, country => 1 );
        $image_link .= '&' if ( length $image_link );
        $image_link .= 'c=m&country=';
        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}        = 'geo_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_countries';
            push @tables, $table_href;
        }
    }

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

    return $self;
}

1;
