package RPS::Import::JohnnyWonder::v1;

use strict;
use warnings;

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

use RPS::Import::ServiceMap;
use Date::Calc qw(Days_in_Month);
use Common::Util qw(normalize_upc normalize_isrc);

use base qw(RPS::Import::MapFaceBase RPS::Import::Importer);

sub _headerIdentifier { ( upc => qr/UPC(\/EAN)?/ ) }

sub _fieldMap {
    {
        labelName        => 'D',
        serviceID        => 'C',
        countryCode      => 'O',
        dateBegin        => 'A',
        productType      => 'P',
        formatType       => 'R',
        mediaType        => 'P',
        artistName       => 'E',
        upc              => 'G',
        albumName        => 'F',
        isrc             => 'K',
        trackName        => 'I',
        units            => 'S',
        price            => 'V',
        currencyCode     => 'V1',
        clientProductID  => 'H',
    }
}

sub _unverifiedFieldMap {{}}

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

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || "";
    my $isrc = $self->_getByFieldName('isrc') || "";

    return RPS::File::Sale::TYPE_TRACK if ( $type =~ /^track|video$/i );
    return RPS::File::Sale::TYPE_TRACK if ( !$type && $isrc );
    return RPS::File::Sale::TYPE_ALBUM if ( $type =~ /^album$/i );

    $self->handleError("Error: Product type '$type' is not supported.", RPS::DB::Item::SaleImportError::kErrorProductType);
}

sub formatType {
    my $self = shift;

    my $type = $self->_getByFieldName('formatType') || "";

    return RPS::File::Sale::FORMAT_DOWNLOAD if ( $type =~ /^download$/i );
    return RPS::File::Sale::FORMAT_STREAM   if ( $type =~ /^interactive streaming$/i );
    return RPS::File::Sale::FORMAT_PERFORMANCE if ( $type =~ /^non-interactive streaming$/i );
    return RPS::File::Sale::FORMAT_RINGTONE if ( $type =~ /ringtones\s+ring/i );
    return RPS::File::Sale::FORMAT_TETHERED if ( $type =~ /tethered download/i );

    $self->handleError("Error: Format type '$type' is not supported.", RPS::DB::Item::SaleImportError::kErrorFormatType);
}

sub mediaType {
    my $self = shift;

    my $type = $self->_getByFieldName('mediaType') || "";

    return RPS::DB::Item::MediaType::kMediaTypeAudio if ( $type =~ /^track|album$/i );
    return RPS::DB::Item::MediaType::kMediaTypeVideo if ( $type =~ /^video$/i );

    $self->handleError("Error: Media type '$type' is not supported.", RPS::DB::Item::SaleImportError::kErrorMediaType);
}

sub serviceID {
    my $self = shift;

    my $retailer = $self->_getByFieldName('serviceID') || "";

    my $service_id = $self->getServiceID( lc($retailer) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc($retailer) };
    return $service_id if $service_id;

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

sub countryCode {
    my $self = shift;

    my $name = lc( $self->_getByFieldName('countryCode') || '' );
    return 'US' unless $name;

    my %country_map = (
            "ivory coast" => "ci",
            "bosnia & herzegovina" => "ba",
            "u.s. virgin islands" => "vi",
            "british virgin islan" => "vg",
            "saint kitts and nevi" => "kn",
            "saint pierre and miq" => "pm",
            "democratic republic" => "cd",
            "guinea- bissau" => "gw",
            "turks and caicos isl" => "tc",
            "saint vincent and th" => "vc",
            "central africa" => "cf",
            "laos" => "la",
            "northern mariana isl" => "mp",
            "curaã§ao" => "cw",
            "palestinian territor" => "ps",
            "micronesia" => "fm",
            "falkland islands" => "fk",
            "unknown" => "us",
            "bes islands" => "bq",
            "sao tome and princip" => "st",
            "british indian ocean" => "io",
        );

    $name = $country_map{lc($name)} if $country_map{lc($name)};
    $name = "cw" if $name =~ /^cura..ao$/;

    if ($name) {
        my $country = Common::Country->Get($name);
        return $country->alpha2() if $country;
    }

    $self->handleError( "Unknown country: '$name'.", RPS::DB::Item::SaleImportError::kErrorCountry );
}

sub currencyCode {
    my $self = shift;

    my $currency = $self->_getByFieldName('currencyCode') || '';
    return 'USD' if $currency =~ /^US\$/;

    return $self->handleError( "Cannot determine currency code from $currency", RPS::DB::Item::SaleImportError::kErrorNonqualifying );
}

my %months = (
    jan => 1, jul => 7,
    feb => 2, aug => 8,
    mar => 3, sep => 9,
    apr => 4, oct => 10,
    may => 5, nov => 11,
    jun => 6, dec => 12,
);

sub _getDates {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || "";

    if ($date =~ /^(\w{3})(\d{4})$/) {
        my ($month, $year) = ($months{lc($1)}, $2);
        my $dateBegin = sprintf("%04d-%02d-01", $year, $month);
        my $dateEnd = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month));

        return ($dateBegin, $dateEnd);
    }

    $self->handleError( "Date not set", RPS::DB::Item::SaleImportError::kErrorNonqualifying );
}

sub price     { abs( shift->_getByFieldName('price') || 0 ) }
sub unitPrice { abs shift->SUPER::unitPrice }
sub units {
    my $self = shift;

    my $units = $self->_getByFieldName('units') || 0;
    my $price = $self->_getByFieldName('price') || 0;

    if ( $price > 0 ) {
        $units = $units ? abs($units) : 1;
    } elsif ( $price < 0 ) {
       $units = $units ? -1 * abs($units) : -1;
    }

    return $units;
}

sub _mapFaceProductType { 'productType'}
sub _mapFaceServiceID   { 'serviceID' }
sub _mapFaceCountryCode { 'countryCode' }
sub _mapFaceFormatType  { 'formatType' }
sub _mapFaceMediaType   { 'mediaType' }

1;
