package RPS::Import::OrchardBase;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

use lib '/app/tools/rps/lib';
use RPS::Import::Importer;
use RPS::Import::ServiceMap;
use base 'RPS::Import::Importer';

sub _parseServiceCountry {
    my $self = shift;
    my ( $service, $errors ) = @_;
    my $orig_service = $service;
    my $countryCode;

    $service = lc $service;

    my $raw_value = $service;
    my $country;

    # we expect some non-word chars, but not with spaces around them
    my @service_country_parts = split( " ", $service );

    # First see if the values are tab delimited
    if ( $service =~ /:::/ ) {
        ( $service, $country ) = split( ":::", $service );
    }

    # Then try to parse by word count.
    elsif ( @service_country_parts == 2 ) {
        $country = $service_country_parts[1];
    } elsif ( @service_country_parts == 3 ) {
        $country = $service_country_parts[2];
        $service = $service_country_parts[0] . " " . $service_country_parts[1];
    } elsif ( @service_country_parts == 4 ) {
        $service = $service_country_parts[0] . " " . $service_country_parts[1];
        $country = $service_country_parts[2] . " " . $service_country_parts[3];
    } else {
        $country = $service;
    }

    my $backup_service = $service;
    $backup_service =~ s/\s.*$//;

    # by now if there are two or more words separated by a space, then the first chunk
    # is the service and the rest is the country

    $country =~ s/belguim/belgium/;
    $country =~ s/luxambourg/luxembourg/;
    $country = "japan"                                 if ( $raw_value =~ /japan/i );
    $country = "japan"                                 if ( $raw_value =~ /jp/i );
    $country = "germany"                               if ( $raw_value =~ /germany/i );
    $country = "united kingdom"                        if ( $raw_value =~ /uk/ );
    $country = "united kingdom"                        if ( $raw_value =~ /gb/ );
    $country = "spain"                                 if ( $raw_value =~ /spain/ );
    $country = "canada"                                if ( $raw_value =~ /canada/i );
    $country = "us"                                    if ( $country =~ /\sus/i );
    $country = "france"                                if ( $raw_value =~ /france/i );
    $country = "italy"                                 if ( $raw_value =~ /italy/i );
    $country = "Congo, the Democratic Republic of the" if ( $raw_value =~ /congo, ?democratic republic of the/i );
    $country = "Lao People's Democratic Republic"      if ( $raw_value =~ /laos/i );
    $country = "Côte d'Ivoire"                        if ( $raw_value =~ /c\w+te d\\'ivoire/i );
    $country = "TW"                                    if ( $raw_value =~ /taiwan,province of china/i );
    $country = "VI"                                    if ( $raw_value =~ /virgin islands,u.s./i );
    $country = "CI"                                    if ( $country =~ /c\x93te d'ivoire/i );

    if ($country) {
        if ( my $obj = Common::Country->Get($country) ) {
            $countryCode = $obj->alpha2();
        } else {
            die "Unknown country '$country'";

            # It seemed that previous versions of this importer defaulted to US if
            # a country code wasn't found.  This didn't seem right so I've disabled it
            # when this was converted to the new Country API
            #$countryCode = 'US';
        }
    } else {
        $countryCode = "US";
    }

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

    $serviceID = $self->getServiceID($backup_service) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $backup_service }
      if ( $serviceID eq "" );

    unless ( $serviceID || $errors->{$service} ) {
        $self->errstr( "unknown service: " . $service . " : " . $orig_service );
        print STDERR "unknown service: " . $service . " : " . $orig_service . "\n";
        $errors->{$service} = 1;
    }
    $countryCode = "GB" if ( $_[0] =~ /\sUK/ );

    unless ( $countryCode || $errors->{$country} ) {
        $self->errstr( 'unknown country:' . $country );
        print STDERR "unknown country: '$country' ($_[0])\n";
        $errors->{$country} = 1;
    }
    return ( $serviceID, $countryCode );
}

sub _getDates {
    my $self = shift;
    my $date = shift;
    my ( $month, $year );
    my $offset = 0;

    if ( $date =~ m/^(\d+)$/ ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
    }

    if ( $date =~ m/^(\d{4})q([1234]$)/i ) {
        $month  = $2 * 3;
        $year   = $1;
        $offset = 2;
    } elsif ( $date =~ m/Q([1234])(\d\d)/i ) {
        $month  = $1 * 3;
        $year   = $2 + 2000;
        $offset = 2;
    } elsif ( $date =~ m/^(\d{4})m(\d{1,2})$/i ) {
        $month = $2;
        $year  = $1;
    } elsif ( $date =~ m/^(\d{4})-(\d{1,2})-(\d{1,2})$/i ) {
        $month = $2;
        $year  = $1;
    } elsif ( $date =~ m/(\w*) (\d{4})/ ) {
        my %months = (
            Jan => 1,
            Feb => 2,
            Mar => 3,
            Apr => 4,
            May => 5,
            Jun => 6,
            Jul => 7,
            Aug => 8,
            Sep => 9,
            Oct => 10,
            Nov => 11,
            Dec => 12
        );
        ( $month, $year ) = $date =~ m/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w* (\d{4})/i;
        $month = $months{$month};
    } elsif ( $date =~ m/(\w*)-(\d{4})/ ) {
        my %months = (
            Jan => 1,
            Feb => 2,
            Mar => 3,
            Apr => 4,
            May => 5,
            Jun => 6,
            Jul => 7,
            Aug => 8,
            Sep => 9,
            Oct => 10,
            Nov => 11,
            Dec => 12
        );
        ( $month, $year ) = $date =~ m/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*-(\d{4})/i;
        $month = $months{$month};
    } elsif ( $date =~ m/(\w{3})-(\d{2})/ ) {
        my %months = (
            Jan => 1,
            Feb => 2,
            Mar => 3,
            Apr => 4,
            May => 5,
            Jun => 6,
            Jul => 7,
            Aug => 8,
            Sep => 9,
            Oct => 10,
            Nov => 11,
            Dec => 12
        );
        ( $month, $year ) = $date =~ m/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*-(\d{2})/i;
        $month = $months{$month};
        $year += 2000;
    }

    return unless ( $year && $month );
    return ( sprintf( "%04d-%02d-01", $year, $month - $offset ),
        sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) ) );
}

###
1;    # Play nicely.
###
