package RPS::Import::Sony::v35;

use strict;

use lib '/app/tools/rps/lib';

use RPS::File::Sale;
use RPS::Import::ServiceMap;
use RPS::DB::Item::MediaType;

use base 'RPS::Import::MapFaceBase';
use base 'RPS::Import::Importer';

sub physical { return 2; }    # A value of 2 means that this file could contain digital and/or physical sales.

sub _fieldMap {
    return {
        serviceID        => 'V',
        countryCode      => 'T',
        dateBegin        => 'F',
        dateEnd          => 'G',
        productType      => 'N',
        formatType       => 'U',
        clientProductID  => 'I',
        isrc             => 'P',
        trackName        => 'R',
        units            => 'AD',
        currencyCode     => 'D',
        price            => 'AE',
        wholesalePrice   => 'X',
        totalRevenue     => 'AE',
        mediaType        => 'N',
        sales            => 'AD',
        priceLevel       => 'W'
    }
}

sub _unverifiedFieldMap {
    return {
        _artistName      => 'K',
        _trackArtist     => 'Q',
        _albumName       => 'L',
        _trackName       => 'M'
    }
}

my %formatMap = (
    'Digital Ad Supported Streaming' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM,
    },
    'Digital Breakage Conditional' => {
        format_type  => RPS::File::Sale::FORMAT_TETHERED
    },
    'Digital Breakage Metadata' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Breakage Mobile' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Breakage Online' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Breakage Streaming Ad Supported' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Breakage Streaming Paid' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Download Conditional' => {
        format_type  => RPS::File::Sale::FORMAT_TETHERED
    },
    'Digital Downloads Permanent' => {
        format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
    },
    'Digital Locker Downloads' => {
        format_type  => RPS::File::Sale::FORMAT_TETHERED
    },
    'Digital Paid Subscription Streaming' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Settlement Ad Supported Streaming' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Settlement Conditional' => {
        format_type  => RPS::File::Sale::FORMAT_TETHERED
    },
    'Digital Settlement Paid Subscription Streaming' => {
        format_type  => RPS::File::Sale::FORMAT_STREAM
    },
    'Digital Telecommunication Sale' => {
        format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
    },
    'PP&B Label and Performer Share' => {
        format_type  => RPS::File::Sale::FORMAT_PERFORMANCE
    }
);

my %productMediaMap = (
    CD => {
        product_type => RPS::File::Sale::TYPE_CD,
        media_type => RPS::DB::Item::MediaType::kMediaTypeAudio
    },
    DD => {
        product_type => RPS::File::Sale::TYPE_ALBUM,
        media_type => RPS::DB::Item::MediaType::kMediaTypeAudio
    },
    DDVDV => {
        product_type => RPS::File::Sale::TYPE_ALBUM,
        media_type => RPS::DB::Item::MediaType::kMediaTypeVideo
    },
    MSTR => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type => RPS::DB::Item::MediaType::kMediaTypeAudio
    },
    SDD => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type => RPS::DB::Item::MediaType::kMediaTypeAudio
    },
    VDD => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type => RPS::DB::Item::MediaType::kMediaTypeVideo
    }
);

sub _headerIdentifier { units => 'Units' }

sub countryCode {
    my $self = shift;

    my $name    = $self->_getByFieldName('countryCode');
    my $country = Common::Country->Get($name);
    if ($country) {
        return $country->alpha2();
    } else {
        return $name;
    }
}

sub serviceID {
    my $self    = shift;
    my $service = $self->_getByFieldName('serviceID');
    $service = "sony" if ! $service;

    my $serviceID = $self->getServiceID( lc($service) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };

    return $serviceID if ($serviceID);

    return $self->handleError( "Unknown service: $service", RPS::DB::Item::SaleImportError::kErrorService );
}

sub currencyCode {
    return shift->_getByFieldName('currencyCode');
}


sub isrc {
    my $self = shift;
    my $isrc = $self->_getByFieldName('isrc');

    if ( $isrc =~ /^[a-z]/i ) {
        return $isrc;
    }
}

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');

    if ( my ($year, $month, $day) = $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub _getDateEnd {
    my $self = shift;
    my $date = $self->_getByFieldName('dateEnd');

    if ( my ($year, $month, $day) = $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub productType {
    my $self = shift;
    
    my $configuration = $self->_getByFieldName('productType');
    my $productType = $productMediaMap{$configuration}->{product_type};

    if ($productType) {
        return $productType;
    } 
    else {
        # Because this file format can include both digital and physical products
        # and other fields depend on us knowing if this one is physical or digital,
        # we must throw an error if the product type is not set.
        return $self->handleError( "Product type not set for config: " . $configuration, RPS::DB::Item::SaleImportError::kErrorNonqualifying );
    }
}

sub mediaType {
    my $self = shift;

    my $configuration = $self->_getByFieldName('mediaType');
    my $mediaType = $productMediaMap{$configuration}->{media_type};

    if ($mediaType) {
        return $mediaType;
    } 
    else {
        return $self->handleError( "Media type not set for config: " . $configuration, RPS::DB::Item::SaleImportError::kErrorMediaType );
    }
}

sub artistName {
    my $self   = shift;
    
    my $productType = $self->productType();

    if ($productType eq RPS::File::Sale::TYPE_TRACK) {
       return $self->_getByFieldName('_trackArtist');
    }
    else {
        return $self->_getByFieldName('_artistName');
    }
}

sub albumName {
    my $self = shift;
    
    my $productType = $self->productType();

    if ($productType eq RPS::File::Sale::TYPE_TRACK) {
       return $self->_getByFieldName('_trackName');
    }
    else {
        return $self->_getByFieldName('_albumName');
    }
}

sub trackName {
    return shift->_getByFieldName('trackName');
}

sub _isValidSaleRecord {
    my $self = shift;

    return ( 
        ($self->price() || $self->totalRevenue()) && 
        ($self->trackName() || $self->albumName()) &&
        $self->_getByFieldName('units')
    );
}

################## Digital-only Fields #####################################

sub units {
    my $self = shift;

    if ( RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        my $units = $self->_getByFieldName('units');
        $units =~ s/\.0+$//g;    # remove any trailing decimal zeroes
        $units =~ s/,//g;

        my $price = $self->price;

        $units = abs($units);

        if ( $price < 0 ) {
            $units *= -1;
        }

        return $units;
    }
}

sub price {
    my $self = shift;

    if ( RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        my $price = $self->_getByFieldName('price');
        $price =~ s/\$//g;
        $price =~ s/,//g;

        return $price;
    }
}

sub formatType {
    my $self = shift;

    if ( RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        my $configuration = $self->_getByFieldName('formatType');
        my $formatType = $formatMap{$configuration}->{format_type};
        
        if ($formatType) {
            return $formatType;
        }
        else {
            return $self->handleError( "Format type not set for config: " . $configuration, RPS::DB::Item::SaleImportError::kErrorFormatType );
        }
    }
}

################## Physical-only Fields #####################################

sub channel {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        return RPS::File::Sale::CHANNEL_RETAIL;
    }
}

sub priceLevel {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        my $priceLevel = $self->_getByFieldName('priceLevel');
        if ( $priceLevel =~ /^full$/i ) {
            return RPS::File::Sale::PLEVEL_FULL;
        } 
        elsif ( $priceLevel =~ /^mid$/i ) {
            return RPS::File::Sale::PLEVEL_MID;
        } 
        elsif ( $priceLevel =~ /^budget$/i ) {
            return RPS::File::Sale::PLEVEL_BUDGET;
        }
        return $self->handleError( "Unable to determine price level from ($priceLevel)", RPS::DB::Item::SaleImportError::kErrorNonqualifying );
    }
}

sub wholesalePrice {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        return $self->_getByFieldName('wholesalePrice');
    }
}

sub sales {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        if ( $self->totalRevenue >= 0 ) {
            return abs( $self->_getByFieldName('sales') );
        }
    }
}

sub salesRevenue {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        if ( $self->totalRevenue > 0 ) {
            return abs( $self->totalRevenue );
        }
    }
}

sub returns {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        if ( $self->totalRevenue < 0 ) {
            return abs( $self->_getByFieldName('sales') );
        }
    }
}

sub returnsRevenue {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        if ( $self->totalRevenue < 0 ) {
            return abs( $self->totalRevenue );
        }
    }
}

sub totalRevenue {
    my $self = shift;

    if ( !RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        my $revenue = $self->_getByFieldName('totalRevenue');
        $revenue =~ s/,//g;
        return $revenue;
    }
}

## MapFace

sub _mapFaceServiceID {
    return ('serviceID');
}

sub _mapFaceCountryCode {
    return ('countryCode');
}

sub _mapFaceProductType {
    return ('productType');
}

sub _mapFaceFormatType {
    return ('formatType');
}

sub _mapFaceMediaType {
    return ('mediaType');
}

1;
