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

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

use lib '/app/tools/data_classes/lib';

use lib '/app/tools/bookpub/lib';
use BookPub::Analytics::ReportLib;    # for pie charts
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);

    my $pie_count      = 0;
    my $base_image_url = "";
    my $data           = {};
    my @pies           = ();
    my @tables         = ();

    # --------------------------
    # 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 );

    # !!! Should transform the pie chart utils into an XMLObject.
    #
    # --------------------------
    # pie chart - top services
    # --------------------------
    my $top_services = $stats_obj->GetTopRanking( category => 'service' );
    my $service_names = $self->_getServiceMap();

    foreach my $service_ref (@$top_services) {
        next if ( $service_ref->Revenue <= 0 );

        push @{ $data->{labels} }, $service_names->{ $service_ref->ID };
        push @{ $data->{ids} },    $service_ref->ID;
        push @{ $data->{data} },   $service_ref->Revenue;
    }

    if ( $data && defined $data->{data} ) {

        # !!! In my opinion, this is a hack.
        # !!! We'll have to explore ways to avoid embedding urls in the pie chart.
        #
        my $image_link = $args{commandObj}->getParamsAsString( c => 1 );
        $image_link .= '&' if ( length $image_link );
        $image_link .= 'c=s&service=';

        #        my $image_link = "view=s&" . $self->GetPartialQueryString(view => 1) . "&service=";
        my $pie_href = GetPieChart(
            labels         => $data->{labels},
            data           => $data->{data},
            image_map_link => $image_link,
            label_ids      => $data->{ids},
        );
        my $xml_href = {};
        $xml_href->{PieName}        = "top_services";
        $xml_href->{ImageSrc}       = $pie_href->{image_src};
        $xml_href->{ImageMap}       = $pie_href->{image_map};
        $xml_href->{Legend}->{Item} = $pie_href->{legend_xml};

        push @pies, $xml_href;

        # we have to keep track of the image we created
        # and how many we've created
        $base_image_url = $pie_href->{image_src};
        $pie_count++;
    }

    # --------------------------
    # pie chart - top formats
    # --------------------------
    my $top_formats = $stats_obj->GetTopRanking( category => 'format' );
    my $format_names = $stats_obj->FormatMap();
    $data = {};

    foreach my $format_ref (@$top_formats) {
        next if ( $format_ref->Revenue <= 0 );

        push @{ $data->{labels} }, $format_names->{ $format_ref->ID };
        push @{ $data->{ids} },    $format_ref->ID;
        push @{ $data->{data} },   $format_ref->Revenue;
    }

    if ( $data && defined $data->{data} ) {
        my $image_link = $args{commandObj}->getParamsAsString( c => 1 );
        $image_link .= '&' if ( length $image_link );
        $image_link .= 'c=f&format=';

        #        my $image_link = "view=f&" . $self->GetPartialQueryString(view => 1) . "&format=";
        my $pie_href = GetPieChart(
            labels         => $data->{labels},
            data           => $data->{data},
            image_map_link => $image_link,
            label_ids      => $data->{ids},
            image_src      => $base_image_url,
            chart_num      => $pie_count,
        );
        my $xml_href = {};
        $xml_href->{PieName}        = "top_formats";
        $xml_href->{ImageSrc}       = $pie_href->{image_src};
        $xml_href->{ImageMap}       = $pie_href->{image_map};
        $xml_href->{Legend}->{Item} = $pie_href->{legend_xml};

        push @pies, $xml_href;

        # we have to keep track of dynamic images
        $base_image_url = $pie_href->{image_src};
        $pie_count++;
    }

    # -------------------------
    # table data - top books
    # -------------------------
    $self->_getTopProducts(
        tables    => \@tables,
        stats_obj => $stats_obj,
        prod_type => PROD_BOOK,
        limit     => 10
    );

    # -------------------------
    # table data - top chapters
    # -------------------------
    $self->_getTopProducts(
        tables    => \@tables,
        stats_obj => $stats_obj,
        prod_type => PROD_CHAP,
        limit     => 10
    );

    # -------------------------
    # table data - top authors
    # -------------------------
    $self->_getTopAuthors(
        tables    => \@tables,
        stats_obj => $stats_obj,
        limit     => 10
    );

    # -------------------------
    # file summary
    # -------------------------
    # my $file_summary = $stats_obj->GetServiceStatus(%params);
    # $months->{$month} = substr(Date::Calc::Month_to_Text($month), 0, 3)
    my ( undef, $start_month, undef ) = split( '-', $self->{_period}->StartDate );
    my ( undef, $end_month,   undef ) = split( '-', $self->{_period}->EndDate );

    # my $fs_labels = ['Apr 2005','May 2005','Jun 2005'];
    my $fs_labels = [];
    for ( my $mon = $start_month ; $mon <= $end_month ; $mon++ ) {
        my $abbr_mon = substr( Date::Calc::Month_to_Text($mon), 0, 3 );
        push @$fs_labels, sprintf( "%s %d", $abbr_mon, $self->{_period}->Year );
    }
    my $fs_order = [ 'Service', 'Data' ];

    # my $fs_data = [ {Service => 'iTunes', Data => [0,1,0]} ];
    my $table_data = [];

    foreach my $service_id ( sort { lc $service_names->{$a} cmp lc $service_names->{$b} } keys %$service_names ) {
        next if ( $service_id == 0 );

        my $href = {};
        $href->{Service} = $service_names->{$service_id};
        $href->{Data} = $stats_obj->GetServiceFileStatus( service_id => $service_id, %{ $self->{_statParams} } );
        push @$table_data, $href;
    }

    my $table_href = CreateTableXML( data => $table_data, order => $fs_order, labels => $fs_labels );

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

    $self->{Pies}{Pie} = \@pies;
    $self->{Tables}{Table} = \@tables if ( @pies or $total_metric->Revenue < 0 );

    return $self;
}

1;
