#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::Report::MissedSales;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::FormObject;
use Common::Assert;
use Common::Client;
use Common::Locale;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ClientOptions;
use RPS::DB::Item::ConsolidatedArtistRoyaltyRunMissedSaleLog;
use RPS::DB::Item::Format;
use RPS::DB::Item::IncomeSource;
use RPS::DB::Item::ProductType;
use RPS::File::Sale;

use base 'RPS::Report';

sub _baseXMLName { 'MissedSale' }

sub _getDBItem() {
    my $self  = shift;
    my %args  = @_;
    my $runID = $args{runID};

    return RPS::DB::Item::ConsolidatedArtistRoyaltyRunMissedSaleLog->GetByRunID($runID);
}

sub _reportColumns {
    my $self = shift;

    my $locale = Common::Client::Current()->Locale();
    my $cc     = $locale->currencyFormat()->currencyCode();
    my @columnArray = (
        "CatalogNumber"       => "Catalog #",
        "ClientAlbumID"       => "Client Album ID",
        "LabelName"           => "Label Name",
        "AlbumTitle"          => "Album Title",
        "AlbumArtist"         => "Album Artist",
        "AlbumDateCreated"    => "Album Date Created",
        "AlbumID"             => "RS Album ID",
        "TrackTitle"          => "Track Title",
        "TrackArtist"         => "Track Artist",
        "TrackID"             => "RS Track ID",
        "ArtistContractTitle" => "Contract Title",
        "ArtistContractID"    => "RS Contract ID",
        "ProductType"         => "Product Type",
        "FormatTypeCode"      => "Format Type Code",
        "FormatType"          => "Format Type",
        "Units"               => "Units",
    );

    if ( RPS::DB::Item::ClientOptions->Get( 'gross_revenue' ) ) {
        push( @columnArray,
	    "GrossRevenueRaw" => "Gross Revenue ($cc)"
        );
    }

    push( @columnArray,
        "TotalRevenueRaw"     => "Net Revenue ($cc)",
        "Reason"              => "Reason",
        "Details"             => "Details",
        "AlbumCustom1"        => "Album Custom 1",
        "AlbumCustom2"        => "Album Custom 2",
        "AlbumCustom3"        => "Album Custom 3",
        "TrackCustom1"        => "Track Custom 1",
        "TrackCustom2"        => "Track Custom 2",
        "TrackCustom3"        => "Track Custom 3",
    );

    return @columnArray;
}

sub _fillInHash {
    my ( $self, $logLine ) = @_;

    my $locale = Common::Client::Current()->Locale();

    my %data;

    $data{AlbumArtist}         = $logLine->album_artist;
    $data{AlbumCustom1}        = $logLine->album_custom_1;
    $data{AlbumCustom2}        = $logLine->album_custom_2;
    $data{AlbumCustom3}        = $logLine->album_custom_3;
    $data{AlbumDateCreated}    = substr($logLine->album_date_created, 0, 10);
    if ($logLine->album_id) {
        $data{AlbumID}         = $logLine->album_id;
    }
    $data{AlbumTitle}          = $logLine->album_title;
    if ($logLine->artist_contract_id) {
        $data{ArtistContractID}    = $logLine->artist_contract_id;
    }
    $data{ArtistContractTitle} = $logLine->artist_contract_title;
    $data{CatalogNumber}       = $logLine->catalog_number;
    $data{ClientAlbumID}       = $logLine->client_album_id;
    $data{Details}             = $logLine->details;

    my $incomeSourceID = _determineIncomeSourceID($logLine->product_type_id, $logLine->format_type);
    $data{FormatTypeCode}      = _idToIncomeSource($incomeSourceID);
    $data{FormatType}          = _idToFormatType($logLine->format_type);

    $data{LabelName}           = $logLine->label_name;
    $data{ProductType}         = _idToProductType($logLine->product_type_id);
    $data{Reason}              = $logLine->reason;

    if ( RPS::DB::Item::ClientOptions->Get( 'gross_revenue' ) ) {
        my $grossRevenue    = "N/A";
        my $grossRevenueRaw = "N/A";
        if ($logLine->gross_revenue) {
            $grossRevenue = $locale->formatMoney( $logLine->gross_revenue );
            $grossRevenueRaw = $locale->formatNumber( $logLine->gross_revenue, '.2' )
        }
        $data{GrossRevenue}        = $grossRevenue;
        $data{GrossRevenueRaw}     = $grossRevenueRaw;
    }

    my $totalRevenue    = "N/A";
    my $totalRevenueRaw = "N/A";
    if ($logLine->total_revenue) {
        $totalRevenue = $locale->formatMoney( $logLine->total_revenue );
        $totalRevenueRaw = $locale->formatNumber( $logLine->total_revenue, '.2' )
    }
    $data{TotalRevenue}        = $totalRevenue;
    $data{TotalRevenueRaw}     = $totalRevenueRaw;

    $data{TrackArtist}         = $logLine->track_artist;
    $data{TrackCustom1}        = $logLine->track_custom_1;
    $data{TrackCustom2}        = $logLine->track_custom_2;
    $data{TrackCustom3}        = $logLine->track_custom_3;
    if ($logLine->track_id) {
        $data{TrackID}         = $logLine->track_id;
    }
    $data{TrackTitle}          = $logLine->track_title;
    $data{Units}               = $locale->formatNumber( $logLine->units );

    return \%data;
}


my $gFormatTypeIDMap;

sub _idToFormatType {
    my ($id) = @_;

    if ( !$gFormatTypeIDMap ) {
        $gFormatTypeIDMap = {};

        my $all = RPS::DB::Item::Format->GetAll();
        while ( my $ft = $all->next() ) {
            $gFormatTypeIDMap->{ $ft->format_type } = $ft->format_name;
        }
        # We're going to override a couple of PI format names
        $gFormatTypeIDMap->{ RPS::File::Sale::FORMAT_EPHEMERAL } = 'Ephemeral (Performance Income)';
        $gFormatTypeIDMap->{ RPS::File::Sale::FORMAT_NON_EPHEMERAL } = 'Non-Ephemeral (Performance Income)';
    }

    # Let's use the ID as the default format name,
    # just in case we don't find a match.
    my $formatTypeName = $id;

    if ( $gFormatTypeIDMap->{$id} ) {
        $formatTypeName = $gFormatTypeIDMap->{$id};
    }

    return $formatTypeName;
}


my $gIncomeSourceIDMap;

sub _idToIncomeSource {
    my ($id) = @_;

    if ( !$gIncomeSourceIDMap ) {
        $gIncomeSourceIDMap = {};

        my $all = RPS::DB::Item::IncomeSource->GetAll();
        while ( my $is = $all->next() ) {
            $gIncomeSourceIDMap->{ $is->income_source_id } = $is->name;
        }
    }

    # Let's use the ID as the default income source name,
    # just in case we don't find a match.
    my $incomeSourceName = $id;

    if ( $gIncomeSourceIDMap->{$id} ) {
        $incomeSourceName = $gIncomeSourceIDMap->{$id};
    }

    return $incomeSourceName;
}


my $gProductTypeIDMap;

sub _idToProductType {
    my ($id) = @_;

    if ( !$gProductTypeIDMap ) {
        $gProductTypeIDMap = {};

        my $all = RPS::DB::Item::ProductType->GetAll();
        while ( my $pt = $all->next() ) {
            $gProductTypeIDMap->{ $pt->product_type_id } = $pt->description;
        }
    }

    my $productTypeName = $id;

    if ( $gProductTypeIDMap->{$id} ) {
        $productTypeName = $gProductTypeIDMap->{$id};
    }

    return $productTypeName;
}


# Copied from RPS::ArtistRoyalty::Fast::Script::MapSales
# with some small modifications for this report.
sub _determineIncomeSourceID {
    my ( $productType, $formatType ) = @_;
    my $incomeSourceID;
    $formatType  = uc($formatType);
    $productType = uc($productType);

    if ( 'V' eq $formatType ) {
        if ( '4' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalTrack;
        }
    } elsif ( 'D' eq $formatType ) {
        if ( '4' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalTrack;
        } elsif ( '3' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalAlbum;
        }
    } elsif ( 'H' eq $formatType ) {
        if ( '4' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalTrackPremium;
        } elsif ( '3' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalAlbumPremium;
        }
    } elsif ( 'I' eq $formatType ) {
        if ( '4' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalTrackUpgrade;
        } elsif ( '3' eq $productType ) {
            $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalAlbumUpgrade;
        }
    } elsif ( 'S' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalStream;
    } elsif ( 'T' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDigitalTethered;
    } elsif ( 'R' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceRingtone;
    } elsif ( 'B' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceBackground;
    } elsif ( 'P' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceVPD;
    } elsif ( 'E' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceDualDownload;
    } elsif ( 'J' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceJukebox;
    } elsif ( 'O' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourcePerformanceIncome;
    } elsif ( 'L' eq $formatType
        || '!' eq $formatType
        || '@' eq $formatType
        || '#' eq $formatType
        || '$' eq $formatType
        || '%' eq $formatType
        || '[' eq $formatType
        || ']' eq $formatType
        || ':' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceEphemeral;
    } elsif ( 'N' eq $formatType
        || '&' eq $formatType
        || '*' eq $formatType
        || '(' eq $formatType
        || ')' eq $formatType
        || '_' eq $formatType
        || '{' eq $formatType
        || '}' eq $formatType
        || ';' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceNonEphemeral;
    } elsif ( 'X' eq $formatType ) {
        $incomeSourceID = RPS::DB::Item::IncomeSource::kIncomeSourceOrchardSync;
    }

    return $incomeSourceID;
}

###
1;    #
###
