package RPS::Import::WMG::Util;

use strict;

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

use lib '/app/tools/data_classes/lib';
use Client::Service;

use lib '/app/tools/rps/lib';
use RPS::File::Sale;

use constant WMG                   => 21;
use constant ERROR                 => 'Mapping Error';
use constant TABLE_FORMAT_WIRELESS => 'wireless_format_map';
use constant TABLE_BILLTO_SELLTO   => 'wireless_billto_sellto';

my %WIRELESS_RS_FORMAT_MAP  = ();
my %WIRELESS_WMG_FORMAT_MAP = ();
my %WIRELESS_FORMAT_MAP     = ();
my %WIRED_FORMAT_MAP        = ();
my %WIRED_PRICE_TYPE        = ();

my $DB = Common::RSDB->new( client_id => WMG );

sub errstr {
    return ERROR;
}

# pass the rs-format_id get their format_name back
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWirelessFormatName(FORMAT_ID)"
sub getWirelessFormatName {
    my $formatID = shift;
    _getWirelessFormatMap() unless %WIRELESS_FORMAT_MAP;

    return $WIRELESS_RS_FORMAT_MAP{$formatID} || undef;
}

# pass the wmg-format_name get an rs-format_id back
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWirelessFormatNameFromWMG(WMG_FORMAT_NAME)"
sub getWirelessFormatNameFromWMG {
    my $formatName = lc shift;
    _getWirelessFormatMap() unless %WIRELESS_FORMAT_MAP;

    return $WIRELESS_WMG_FORMAT_MAP{$formatName} || undef;
}

# pass the potentially ugly format name from a sales file and get an rs-format_id back
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWirelessFormatTypeID('FORMAT_NAME')"
sub getWirelessFormatTypeID {
    my $format = _clean_format( $_[0] );
    _getWirelessFormatMap() unless %WIRELESS_FORMAT_MAP;

    return $WIRELESS_FORMAT_MAP{$format} ? $WIRELESS_FORMAT_MAP{$format}{type} : undef;
}

# pass the potentially ugly format name from a sales file and get their "price type" back
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWirelessPriceType('FORMAT_NAME')"
sub getWirelessPriceType {
    my $format = _clean_format( $_[0] );
    _getWirelessFormatMap() unless %WIRELESS_FORMAT_MAP;

    return $WIRELESS_FORMAT_MAP{$format} ? $WIRELESS_FORMAT_MAP{$format}{price} : undef;
}

# pass the #rs-format_id and get their price-type
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWiredPriceType('FORMAT_ID')"
sub getWiredPriceType {
    my $fmtID = $_[0];
    _getWiredPriceType() unless %WIRED_PRICE_TYPE;
    $fmtID = 'FREE' if $_[1];

    return defined $WIRED_PRICE_TYPE{$fmtID} ? $WIRED_PRICE_TYPE{$fmtID} : undef;
}

# pass an rs-service_id and get their associated 'DSP' info (code, name)
# perl -MRPS::Import::WMG::Util -le "print join(',', RPS::Import::WMG::Util::getWirelessBillto(SERVICE_ID))"
sub getWirelessBillto {
    my $serviceId = shift;
    my $sth       = $DB->DoCmd(
        'SELECT billto_code, service_name FROM ' . TABLE_BILLTO_SELLTO . " WHERE service_id=$serviceId AND account_type_code='DSP'" );
    return undef unless ( $sth && $sth->rows() );
    my $row = $sth->fetchrow_arrayref();

    return ( $row->[0], $row->[1] );
}

# pass an rs-service_id and their 'billTo' code returned from getWirelessBillto and get their
# associated 'RET' info (code, name)
# perl -MRPS::Import::WMG::Util -le "print join(',',RPS::Import::WMG::Util::getWirelessSellto(SERVICE_ID, BILLTO))"
sub getWirelessSellto {
    my ( $serviceId, $billTo ) = @_;
    return undef unless ( $serviceId && $billTo );

    my $sth =
      $DB->DoCmd( 'SELECT sellto_code, service_name FROM '
          . TABLE_BILLTO_SELLTO
          . " WHERE service_id=$serviceId AND billto_code=$billTo AND account_type_code='RET'" );
    return undef unless ( $sth && $sth->rows() );
    my $row = $sth->fetchrow_arrayref();

    return ( $row->[0], $row->[1] );
}

# this is meant to handle the 3 previous method calls all in one and is only suited for "normal"
# wireless importers that have only 1 billto/sellto and format
sub getWirelessInfo {
    my $serviceId = shift;
    my $format = shift || '';    # optional param

    my ( $billtoOK, $selltoOK );

    my @billto = getWirelessBillto($serviceId);
    if ( $billto[0] ) {
        $billtoOK = 1;
        $selltoOK = getWirelessSellto( $serviceId, $billto[0] ) ? 1 : 0;
    } else {
        $billtoOK = $selltoOK = 0;
    }

    return $format
      ? ( $billtoOK, $selltoOK, getWirelessPriceType($format) )
      : ( $billtoOK, $selltoOK );
}

# used by wireless report
sub getDistributionMedium {
    my ( $format, $serviceID ) = @_;
    return
        $serviceID == Client::Service::DSP_SPRINT       ? 'INWR'
      : $serviceID == Client::Service::DSP_INTEGRA      ? 'KI'
      : $format eq RPS::File::Sale::FORMAT_DUALDOWNLOAD ? 'INWR'
      :                                                   'WR';
}

# pass the rs-format_id and get the output format name
# perl -MRPS::Import::WMG::Util -le "print RPS::Import::WMG::Util::getWirelessFormatName(FORMAT_ID)"
sub getWiredFormatName {
    my $formatID = shift;
    _getWiredFormatMap() unless %WIRED_FORMAT_MAP;

    return $WIRED_FORMAT_MAP{$formatID} || undef;
}

# XML mappings

sub xml_product_type {
    my $format = shift;
    return
        $format eq RPS::File::Sale::FORMAT_DOWNLOAD    ? ''
      : $format eq RPS::File::Sale::FORMAT_TETHERED    ? ''
      : $format eq RPS::File::Sale::FORMAT_STREAM      ? ''
      : $format eq RPS::File::Sale::FORMAT_VIDEO       ? ''
      : $format eq RPS::File::Sale::FORMAT_VIDEOSTREAM ? ''
      : $format eq RPS::File::Sale::FORMAT_RADIO       ? ''
      : $format eq RPS::File::Sale::FORMAT_TELEVISION  ? ''
      :                                                  '';
}

sub getWiredFileContentType {
    my $file_id = shift || return undef;

#my $sql = "SELECT format_type, SUM(units), SUM(price * units * conversion_rate), COUNT(*) FROM ".DB_TABLE." WHERE file_id=$file_id GROUP BY 1";
    my $sql = "SELECT format_type, COUNT(*) FROM sale WHERE file_id=$file_id GROUP BY 1";
    my $sth = $DB->DoCmd($sql);

    return undef unless ( $sth && $sth->rows > 0 );

    my %types = ();
    foreach my $format ( @{ $sth->fetchall_arrayref() } ) {
        $types{ getReleaseContentType( $format->[0] ) } = 1;
    }

    #my ($contentType) = scalar keys %types == 1 ? keys %types : undef;
    my ($contentType) = keys %types;

    return $contentType;
}

sub getUsageTypeCode {
    my $format = shift;

    # currently only video (16) or audio streams (17)
    my $video = join( '|', RPS::File::Sale::FORMAT_VIDEOSTREAM, RPS::File::Sale::FORMAT_VIDEO, 'video' );

    return $format =~ m/^($video)/i ? 16 : 17;
}

sub getReleaseContentType {
    my $format = shift;
    my $ct     = 'Single';

    my $video = join( '|', RPS::File::Sale::FORMAT_VIDEOSTREAM, RPS::File::Sale::FORMAT_VIDEO );
    substr( $ct, 0, 0 ) = 'Video' if ( $format =~ m/^($video)$/i );

    return $ct;
}

# private helper methods

sub _getWirelessFormatMap {
    my $sth = $DB->DoCmd( 'select * from ' . TABLE_FORMAT_WIRELESS );
    while ( my $row = $sth->fetchrow_hashref() ) {
        $WIRELESS_FORMAT_MAP{ $row->{format_name} } = {
            type  => $row->{rs_format_id},
            name  => $row->{client_format_name},
            price => $row->{price_type},
        };

        $WIRELESS_RS_FORMAT_MAP{ $row->{rs_format_id} } = $row->{client_format_name};
        $WIRELESS_WMG_FORMAT_MAP{ lc( $row->{client_format_name} ) } = $row->{rs_format_id};
    }
}

sub _getWiredFormatMap {

    # hard coded here for now - eventually move to db where it can be edited by cs via ui?
    %WIRED_FORMAT_MAP = (
        RPS::File::Sale::FORMAT_DOWNLOAD    => 'PERMDWNL',
        RPS::File::Sale::FORMAT_TETHERED    => 'SUBASON',
        RPS::File::Sale::FORMAT_STREAM      => 'SUBASON',
        RPS::File::Sale::FORMAT_VIDEO       => 'SUBVSON',
        RPS::File::Sale::FORMAT_VIDEOSTREAM => 'SUBVSON',
        RPS::File::Sale::FORMAT_RADIO       => 'SUBASPP',
        RPS::File::Sale::FORMAT_TELEVISION  => 'SUBVSPP',
    );
}

sub _getWiredPriceType {

    # hard coded here for now - eventually move to db where it can be edited by cs via ui?
    %WIRED_PRICE_TYPE = (
        FREE                                => 'Standard/FreeTrial',
        RPS::File::Sale::FORMAT_DOWNLOAD    => 'Standard/Pre-Programmed',
        RPS::File::Sale::FORMAT_TETHERED    => 'Standard/OnDemand',
        RPS::File::Sale::FORMAT_STREAM      => 'Standard/OnDemand',
        RPS::File::Sale::FORMAT_VIDEO       => 'Standard/OnDemand',
        RPS::File::Sale::FORMAT_VIDEOSTREAM => 'Standard/OnDemand',
        RPS::File::Sale::FORMAT_RADIO       => 'Standard/Pre-Programmed',
        RPS::File::Sale::FORMAT_TELEVISION  => 'Standard/Pre-Programmed',
    );
}

sub _clean_format {
    my $format = lc( $_[0] );
    $format =~ s/^\s+//;
    $format =~ s/\s+$//;
    $format =~ s/(er|ne)s\b/$1/;
    $format =~ s/[\W_]*?(tone|ringe)/$1/;         # master-tone, video ringer
    $format =~ s/exclusive(\S+)/exclusive_$1/;    # fix for regex above
    $format =~ s/non[\W_]+/non/;
    $format =~ s/\W+/_/g;

    return $format;
}

1;
