package Stats::Redshift::Dimension;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Session;

use lib '/app/tools/stats/lib';
use Stats::Redshift::Dimension::Aggregate;

use base 'Stats::Redshift';

__PACKAGE__->mk_accessors(qw/dimensions listing/);

sub _init {
    my $self = shift;
    $self->SUPER::_init();

    my $filesum = Stats::Redshift::Dimension::Aggregate->new( 'agg_file_summary', $self->type );

    my $list = [ $filesum->tablename ];

    my $dims       = $self->_dimensions;
    my $dimensions = [$filesum];
    foreach my $dim ( sort @{$dims} ) {
        foreach my $period (qw/m q y/) {
            my $dimobj = $self->create_dimension_object( $dim, $period );
            push @{$dimensions}, $dimobj;
            push @{$list},       $dimobj->tablename;
        }
    }
    $self->dimensions($dimensions);
    $self->listing($list);
}

sub _dimensions {
    my $self = shift;
    my $dims;
    if ( $self->type eq 'rps' ) {
        $dims = [ (qw/sales product_sales artist_sales summary/) ];
    } else {
        $dims = [ (qw/sales product_sales author_sales summary/) ];
    }
    $dims;
}

sub create_dimension_object {
    my $self   = shift;
    my $dim    = shift;
    my $period = shift;

    my $type      = $self->type;
    my $dim_table = sprintf( "agg_%s_%s", $period, $dim );
    my $dim_agg   = Stats::Redshift::Dimension::Aggregate->new( $dim_table, $type );

    my $key = {
        'm' => 's.month_id',
        'q' => 's.quarter_id',
        'y' => 's.year',
    }->{$period};
    $dim_agg->key($key);

    my $groupby = {
        'dtmv' => {
            'sales'         => [qw/s.product_type s.service_id s.imprint_id s.publisher_id s.format_type s.country_code/],
            'product_sales' => [qw/s.product_id s.product_type s.imprint_id s.publisher_id s.format_type s.service_id s.country_code/],
            'author_sales'  => [qw/bc.contributor_id s.product_type s.imprint_id s.publisher_id s.format_type s.service_id s.country_code/],
            'summary'       => undef,
        },
        'rps' => {
            'sales'         => [qw/s.product_type s.service_id s.label_id s.format_type s.country_code/],
            'product_sales' => [qw/s.product_id s.product_type s.label_id s.format_type s.service_id s.country_code/],
            'artist_sales'  => [qw/s.artist_id s.product_type s.label_id s.format_type s.service_id s.country_code/],
            'summary'       => undef,
        }
    }->{$type}->{$dim};

    if ( defined $groupby ) {
        $dim_agg->groupby($groupby);
    } else {
        $dim_agg->groupby( [$key] );
    }
    $dim_agg;

}

1;
