#------------------------------------------------------------
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Common::Postal::CA;

use strict;
use warnings;

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

use base 'Common::Postal';

my %gState = (
    'AB' => 'Alberta',
    'BC' => 'British Columbia',
    'MB' => 'Manitoba',
    'NB' => 'New Brunswick',
    'NL' => 'Newfoundland and Labrador',
    'NT' => 'Northwest Territories',
    'NS' => 'Nova Scotia',
    'NU' => 'Nunavut',
    'ON' => 'Ontario',
    'PE' => 'Prince Edward Island',
    'QC' => 'Quebec',
    'SK' => 'Saskatchewan',
    'YT' => 'Yukon',
);

# invert the name/abbreviation mappings, so we can
# easily search for state abbreviations

my %gStateAbbr;
map { $gStateAbbr{ lc( $gState{$_} ) } = $_ } keys %gState;

# Add in some alternate matches
# These must be entered in lower case.
$gStateAbbr{'yukon territory'}     = 'YT';
$gStateAbbr{'newfoundland'}        = 'NL';
$gStateAbbr{'quÃ©bec'}           = 'QC';
$gStateAbbr{'québec'}             = 'QC';
$gStateAbbr{'nouvelle-Ã‰cosse'} = 'NS';
$gStateAbbr{'nouvelle-Écosse'}    = 'NS';
$gStateAbbr{'british colombia'}    = 'BC';
$gStateAbbr{'ont'}                 = 'ON';

sub new {
    my ($class) = @_;

    my $self = bless {}, $class;

    return $self;
}

sub country {
    my ( $self, $abbr ) = @_;

    if ( defined($abbr) && $self->getName($abbr) ) {
        return 'CA';
    }

    return $self->SUPER::country();
}

sub getName {
    my ( $self, $abbr ) = @_;

    return $gState{ uc($abbr) };
}

sub getAbbr {
    my ( $self, $name ) = @_;

    return $gStateAbbr{ lc($name) };
}

sub formatPostalCode {
    my ( $self, $postalCode ) = @_;
    my $formatted;

    $postalCode = uc($postalCode);

    # CA postal codes cannot contain the letter O,
    # so if we see one, it's probably meant to be a zero.
    $postalCode =~ s/O/0/g;

    # 'A1A 1A1', valid CA postal code
    if ( $postalCode =~ /^[A-Z]\d[A-Z] \d[A-Z]\d$/ ) {
        $formatted = $postalCode;
    }

    # 'A1A1A1' or 'A1A<some separators>1A1'
    if ( $postalCode =~ /^([A-Z]\d[A-Z])(\d[A-Z]\d)$/ || $postalCode =~ /^([A-Z]\d[A-Z])-(\d[A-Z]\d)$/ ) {
        $formatted = $1 . " " . $2;
    }

    return $formatted;
}

1;
