#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Report::Dynamic::Catalog::Albums;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use lib '/app/tools/report/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/appuser/lib';

use Common::Log;
use Common::Assert;
use File::Path;
use AppUser::DB::Item::AccessLevel;
use Text::CSV::Encoded;
use Report::Dynamic::Parameters;
use RPS::DB::Item::Genre;
use RPS::DB::Item::DynamicReport::Catalog::Albums;
use RPS::DB::Item::ArtistRole;
use RPS::DB::Item::Artist;
use RPS::DB::Item::AlbumAdditionalArtist;

use base 'RPS::Report::Dynamic::Catalog::Base';


sub Type    { 'Albums Only'; }
sub FilenameType { 'Albums' }

# defined at the end of this file
#
sub _ParamClass { 'RPS::Report::Dynamic::Catalog::Albums::Parameters'; }


sub _columns
{
    my ($self) = @_;

    return
    [
        { 
            header => { 
                name => 'album-title' 
            },             
            column => { 
                field => 'title' 
            } 
        },
        { 
            header => { 
                name => 'primary-album-artist', 
            },   
            column => { 
                field => 'primary_artist', 
            } 
        },
        { 
            header => { 
                name => 'secondary-album-artists', 
            }, 
            column => { 
#                field => 'secondary_artist', 
                field => 'album_id', 
                method => '_fetchAlbumSecondaryArtists',
            } 
        },
        { 
            header => { 
                name => 'label-name', 
            },       
            column => { 
                field => 'label_name', 
            } 
        },
        { 
            header => { 
                name => 'catalog-no', 
            },   
            column => { 
                field => 'catalog_number', 
            } 
        },
        { 
            header => { 
                name => 'client-album-id', 
            },  
            column => { 
                field => 'client_album_id', 
            } 
        },
        { 
            header => { 
                name => 'primary-genre', 
            },    
            column => { 
                field => 'genre_primary_id', 
                method => '_idToGenre',
            } 
        },
        { 
            header => { 
                name => 'secondary-genre', 
            },  
            column => { 
                field => 'genre_secondary_id', 
                method => '_idToGenre',
            } 
        },
        { 
            header => { 
                name => 'c-line', 
            },           
            column => { 
                field => 'c_line', 
            } 
        },
        { 
            header => { 
                name => 'p-line', 
            },           
            column => { 
                field => 'p_line', 
            } 
        },
        { 
            header => { 
                name => 'album-status', 
            },           
            column => { 
                field => 'status', 
            } 
        },
        { 
            header => { 
                name => 'album-custom-1', 
            },         
            column => { 
                field => 'custom_1', 
            } 
        },
        { 
            header => { 
                name => 'album-custom-2', 
            },         
            column => { 
                field => 'custom_2', 
            } 
        },
        { 
            header => { 
                name => 'album-custom-3', 
            },         
            column => { 
                field => 'custom_3', 
            } 
        },
        { 
            header => { 
                name => 'album-date-created', 
            },     
            column => { 
                field => 'date_created', 
                excel => 'date:Y-M-D',
                method => '_formatDate',
            } 
        },
        { 
            header => { 
                name => 'album-created-by', 
            },       
            column => { 
                field => 'created_by', 
                method => '_userIDToUserName',
            } 
        },
        { 
            header => { 
                name => 'album-date-modified', 
            },    
            column => { 
                field => 'date_modified', 
                excel => 'date:Y-M-D',
                method => '_formatDate',
            } 
        },
        { 
            header => { 
                name => 'album-modified-by', 
            },      
            column => { 
                field => 'modified_by', 
                method => '_userIDToUserName',
            } 
        },
        { 
            header => { 
                name => 'rs-album-id', 
            },         
            column => { 
                field => 'album_id', 
            } 
        },
    ];
}


sub _getCollection
{
    my ($self) = @_;

    # Dereference the parameters, see if we're constraining
    # the query by date somehow.
    #
    # !!! Don't want to just pass the CGI parameter straight through - That could
    # !!! cause problems...
    #
    my $dateType;
    my $dateTypeParam = $self->parameters()->{Criteria}->DateType();
    if ($dateTypeParam)
    {
        if ('Date Created' eq $dateTypeParam)
        {
            $dateType = 'date_created';
        }
        elsif ('Date Modified' eq $dateTypeParam)
        {
            $dateType = 'date_modified';
        }
    }

    return RPS::DB::Item::DynamicReport::Catalog::Albums->ReportQuery
    (
        dateType => $dateType,
        startDate => $self->parameters()->{Criteria}->StartDate(),
        endDate => $self->parameters()->{Criteria}->EndDate(),
    );
}


# Cache the genres
#
my $gGenreCache;

sub _idToGenre
{
    my ($self, %args) = @_;
    my $rowItem = $args{row};
    my $fieldName = $args{field};

    my $id = $rowItem->$fieldName();

    my $genreName;
    if ($id)
    {
        if (! $gGenreCache)
        {
            $gGenreCache = {};
            my $allGenres = RPS::DB::Item::Genre->GetAll();
            while (my $genre = $allGenres->next())
            {
                $gGenreCache->{ $genre->genre_id() } = $genre->genre_name();
            }
        }

        $genreName = $gGenreCache->{$id};
    }

    return $genreName;
}


# Need to cache the artist roles.
# Not a big table, but it lives in RSCOMMON, and it's going to be expensive
# to keep going back there all the time.
# NOTE that this is not a 'regular' column filter method that takes a row item and stuff.
# 
#
sub _artistRoleFromID
{
    my ($self, $id) = @_;

    my $role;

    if ($id)
    {
        if (! $self->{_ArtistRoleCache})
        {
            $self->{_ArtistRoleCache} = {};

            my $allRoles = RPS::DB::Item::ArtistRole->GetAll();
            while (my $data = $allRoles->next())
            {
                $self->{_ArtistRoleCache}->{ $data->artist_role_id() } = $data->role();
            }
        }

        $role = $self->{_ArtistRoleCache}->{$id};
    }

    return $role;
}


# Another internal cache.
# 
sub _artistFromID
{
    my ($self, $id) = @_;

    my $name;

    if ($id)
    {
        if (! $self->{_ArtistCache})
        {
            $self->{_ArtistCache} = {};

            my $all = RPS::DB::Item::Artist->GetAll();
            while (my $data = $all->next())
            {
                $self->{_ArtistCache}->{ $data->artist_id() } = $data->name();
            }
        }

        $name = $self->{_ArtistCache}->{$id};
    }

    return $name;
}


my $gLastAlbumSecondaryArtists;
my $gLastAlbumSecondaryArtistsID;
sub _fetchAlbumSecondaryArtists
{
    my ($self, %args) = @_;
    my $rowItem = $args{row};
    my $fieldName = $args{field};

    my $id = $rowItem->$fieldName();

    my $outString;
    if ($id)
    {
        # Fetch all the secondary album artists (if there are any).
        #
        # Note that I am not going to cache all of these.
        # We're already caching all the artists and all the roles.
        # However, when outputting the track report, we will need to
        # get the same data more than once.  So we'll just cache the _last_
        # line to make that more efficient.
        #
        if ($id == $gLastAlbumSecondaryArtistsID)
        {
            $outString = $gLastAlbumSecondaryArtists;
        }
        else
        {
            my $all = RPS::DB::Item::AlbumAdditionalArtist->GetAllForAlbumID($id);
            if ($all && $all->size() > 0)
            {
                my @list;
                while (my $data = $all->next())
                {
                    my $name = $self->_artistFromID($data->artist_id());
                    my $role = $self->_artistRoleFromID($data->artist_role_id());
                    push @list, "$name ($role)";
                }
                $outString = join(', ', @list);
            }

            $gLastAlbumSecondaryArtists = $outString;
            $gLastAlbumSecondaryArtistsID = $id;
        }
    }

    return $outString;
}


1;

package RPS::Report::Dynamic::Catalog::Albums::Parameters;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use lib '/app/tools/report/lib';
use lib '/app/tools/rps/lib';
use base 'RPS::Report::Dynamic::Catalog::Parameters';


sub _OptionalData
{
    # !!! Don't have any optional data for the basic catalog report.
    #
    return undef;
}


1;
