package Common::OrchardFetcher::OrchardPeriod;
use strict;
use warnings;

use Date::Calc qw(Days_in_Month);
use POSIX qw(strftime);

use constant kScanMonthly   => 1;
use constant kScanQuarterly => 2;

# Generates a hash containing Orchard-compliant periods for use
# with their Accounting Statement API.  The starting period
# will be 1 (1/1/1999) up to the the year passed in as an
# argument.
#
sub getPeriodHash {
    my $endYear = shift;
    if ( !$endYear ) {
        my $currentDate = strftime "%Y-%m-%d", localtime;
        my ( $currentYear, $currentMonth, $currentDay ) = split( '-', $currentDate );
        $endYear = $currentYear;
    }

    my %periodInfo;

    my @months = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );

    my $period = 1;    # 1/1/1999

    my $_period = $period;

    my $id = 1;
    for my $year ( 1999 .. $endYear ) {
        for my $month ( 1 .. 12 ) {
            my $startDate;
            my $endDate;
            my $periodID;
            my $periodName;

            if ( $month =~ /^(1|4|7|10)$/ ) {
                $startDate = sprintf( "%04d-%02d-01", $year, $month );
                $endDate = sprintf( "%04d-%02d-%02d", $year, $month + 2, Days_in_Month( $year, $month + 2 ) );

                $periodID = join( ",", ($_period), ( $_period + 1 ), ( $_period + 2 ) );

                $periodName =
                    ( $month == 1 ) ? "Q1$year"
                  : ( $month == 4 ) ? "Q2$year"
                  : ( $month == 7 ) ? "Q3$year"
                  :                   "Q4$year";

                $periodInfo{$id}{period}      = $periodID;
                $periodInfo{$id}{period_name} = $periodName;
                $periodInfo{$id}{start_date}  = $startDate;
                $periodInfo{$id}{end_date}    = $endDate;
                $id++;
            }

            $periodID = $_period;

            $periodName                   = $months[ $month - 1 ] . $year;
            $startDate                    = sprintf( "%04d-%02d-01", $year, $month );
            $endDate                      = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
            $periodInfo{$id}{period}      = $periodID;
            $periodInfo{$id}{period_name} = $periodName;
            $periodInfo{$id}{start_date}  = $startDate;
            $periodInfo{$id}{end_date}    = $endDate;
            $id++;

            $_period++;
        }

    }
    return %periodInfo;

}    # _getPeriodHash

1;
