#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::DB::Item::AggMProductSales;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use Common::Assert;
use base 'Common::DB::Item';

use constant kTable => 'agg_m_product_sales';
use constant kDB    => Common::DB::Item::kClientDB;

sub GetTopBooksByPeriods {
    my ( $class, %args ) = @_;
    my $limit = $args{limit} || 5;
    my @periods = ref( $args{periods} ) ? @{ $args{periods} } : ( $args{periods} );

    my $sql = "SELECT month_id, product_id, service_id, country_code, SUM(units) as units, SUM(revenue) as revenue FROM " . kTable;

    $sql .= " WHERE month_id IN ( " . join( ',', @periods ) . " )" if (@periods);

    $sql .= " GROUP BY product_id";
    $sql .= " ORDER BY sum(revenue) DESC ";
    $sql .= " LIMIT $limit";

    Common::Log::Debug("QUERY: $sql");
    return $class->GetAll($sql);
}

sub GetTotalsByPeriod {
    my ( $class, %args ) = @_;
    my @periods   = ref( $args{periods} ) ? @{ $args{periods} } : ( $args{periods} );
    my $serviceID = $args{service_id};
    my $imprintID = $args{imprint_id};

    my $dbo = Common::RSApp::GetClientDB();

    assert(@periods);

    my $sql = "SELECT month_id, SUM(units) as units, SUM(revenue) as revenue FROM " . kTable;

    $sql .= " WHERE month_id IN ( " . join( ',', @periods ) . " )" if (@periods);

    $sql .= " AND service_id = " . $dbo->DBQuote($serviceID) if ($serviceID);
    $sql .= " AND imprint_id = " . $dbo->DBQuote($imprintID) if ($imprintID);

    $sql .= " GROUP BY month_id";
    $sql .= " ORDER BY month_id ";

    Common::Log::Debug("QUERY: $sql");
    return $class->GetAll($sql);
}

sub GetDistinctServiceIDs {
    my $class = shift;

    my $sql = "SELECT DISTINCT(service_id) as service_id FROM " . kTable;

    return $class->SUPER::GetAll($sql);
}

1;
