#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
use strict;

#use warnings;

use PDF::API2;

use File::Path;
use Data::Dumper;
use Getopt::Std;
use Carp;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::RSMath;
use Common::Locale;
use Common::Client;

use lib '/app/tools/rps/lib';
use RPS::Statement::UKMechanical::McpsStatementFull;
use RPS::Statement::UKMechanical::McpsPDF;
use RPS::RoyaltyRun::Status;
use RPS::Payor::Payor;
use RPS::Mechanical::UK::UKMechanicalRun;
use RPS::DB::Item::PriceLevel;
use RPS::DB::Item::ProductType;

use lib '/app/tools/rps/bin/statements';
use TableObj;
use Formats;
use EmbedImage;

$SIG{__DIE__} = \&Carp::confess;

#
# A lot of this code is taken from this tutorial: http://rick.measham.id.au/pdf-api2/
#

# These constants will make it easier to convert between 'regular' units
# and postscript points.
# There are 72 postscript points in an inch, and 25.4 millimeters in an inch.
# All the PDF::API2 methods expect their size or coordinate arguments to be in points.
#
use constant mm => ( 25.4 / 72 );
use constant in => ( 1 / 72 );
use constant pt => 1;

# The standard page dimensions.  Note that we're creating _landscape_ docs.
#
use constant kPageHeight => ( 8.5 / in );
use constant kPageWidth  => ( 11 / in );

# The margins of the page.
# Remember that (0,0) in PDF coordinates is the bottom-left of the page.
#
use constant kLeftMargin   => 0.5 / in;
use constant kBottomMargin => 0.5 / in;
use constant kRightMargin  => ( kPageWidth - ( 0.5 / in ) );
use constant kTopMargin    => ( kPageHeight - ( 0.5 / in ) );

# We are going to keep track of every page we create, so that we
# can go back later and add page numbers
#
my @gPages;

# We'll store a hashref with font info here, once we have a PDF object to work with.
#
my $font;

# This determines how much output we spew forth to STDERR.
# The user can set this with the -V command-line argument.
#
my $gVerbosityLevel = 1;

# Parse the command-line, then create the PDF!
#
my %options;
parseCommandLine( \%options );
createStatementPDF( $options{clientID}, $options{mcpsStatementID}, $options{outputPath} );

# ----------------------------------------------------------------------------------------------

sub createStatementPDF {
    my ( $clientID, $mcpsStatementID, $outFilePath ) = @_;

    # Instantiate the application singleton object.
    #
    my $appSingleton = Common::RSApp->new( clientID => $clientID );

    # Instantiate the McpsStatement object.
    # This object will contain all the info we need to output the statement document.
    #
    my $statement = RPS::Statement::UKMechanical::McpsStatementFull->new( mcpsStatementID => $mcpsStatementID, );

    # If an output file path was not specified, create one out of the statement id.
    #
    if ( !$outFilePath ) {

        $outFilePath = RPS::Statement::UKMechanical::McpsPDF::StatementFileNameFromID($mcpsStatementID);
    }

    # Instantiate the PDF object.
    #
    my $pdf = PDF::API2->new( -file => $outFilePath );

    # Fetch the fonts that we might want to use.
    # Note that every time we define a font, it will get embedded in the document,
    # so we will grab them all here at the very beginning.
    # !!! Be sure to remove any of these we don't actually need...
    #
    # (These are the 'built-in' fonts that all pdf documents get for free. We can embed fancy
    #  fonts if we want to, but that will make the statement files larger...)
    #
    $font = {
        Helvetica => {
            Bold   => $pdf->corefont( 'Helvetica-Bold',    -encoding => 'latin1' ),
            Roman  => $pdf->corefont( 'Helvetica',         -encoding => 'latin1' ),
            Italic => $pdf->corefont( 'Helvetica-Oblique', -encoding => 'latin1' ),
        },
        Times => {
            Bold   => $pdf->corefont( 'Times-Bold',   -encoding => 'latin1' ),
            Roman  => $pdf->corefont( 'Times',        -encoding => 'latin1' ),
            Italic => $pdf->corefont( 'Times-Italic', -encoding => 'latin1' ),
        },
    };

    # Declare the 'cursor' coordinates.  As we go, we'll be updating these values so that the
    # next element shows up in the right place.
    #
    my $x = kLeftMargin;
    my $y = kTopMargin;

    # Create the first (blank) page.
    # Each output subroutine will take the current page as a parameter, and will
    # return the page that they ended on.
    #
    my $page = newPage($pdf);

    # We need to check the run and payor here and in the header,
    # so let's fetch 'em.
    my $run = RPS::Mechanical::UK::UKMechanicalRun->new(
        ukMechanicalRunID => $statement->UKMechanicalRunID(),
        loadSubs          => 0
    );
    my $payorID = $run->PayorID();
    my $payor = RPS::Payor::Payor->new( payorID => $payorID );

    # Add label logo to the first page, if desired
    #
    my $showLogo = $payor->ShowLogo();

    if ( $showLogo == 1 ) {
        my $logoName = $options{clientID} . '/' . $payorID;
        ( $pdf, $page ) = EmbedImage::labelLogo( $pdf, $page, $logoName, kTopMargin, kRightMargin );
    }

    # Each section of the statement will have its own subroutine.
    #
    ( $x, $y, $page ) = header( $pdf, $statement, $payor, $run, $x, $y, $page );
    ( $x, $y, $page ) = details( $pdf, $statement, $x, $y, $page );

    # If the state of the run is not 'COMMITTED' or 'CLOSED', then we want to add a watermark
    # to the pages so that our users don't mail this statement out.
    #
    my $run = RPS::Mechanical::UK::UKMechanicalRun->new(
        ukMechanicalRunID => $statement->UKMechanicalRunID(),
        loadSubs          => 0
    );
    if (   RPS::RoyaltyRun::Status::kCommitted != $run->Status()
        && RPS::RoyaltyRun::Status::kClosed != $run->Status() ) {
        addDraftWatermark($pdf);
    }

    # Now add the page numbers, and other 'footer' stuff
    #
    addFooter($pdf);

    # All done, save and clean up
    #
    $pdf->save();
    $pdf->end();
}

sub header {
    my ( $pdf, $statement, $payor, $run, $x, $y, $page ) = @_;

    my $text = $page->text();

    # Step 1 - Put the text 'UK Mechanical Royalty Statement' at the top of the page.
    #
    $y = printTextCentered( $text, $y, 'UK Mechanical Royalty Statement', $font->{Helvetica}{Bold}, 12 / pt );

    # Now print the run label.
    #

    $y -= 9 / pt;

    my $mcpsScheme = $statement->McpsScheme();
    my $startTime  = $run->StartTime();
    $startTime = formatDate($startTime);

    my $runLabel = "MCPS $mcpsScheme Statement      Date: $startTime";

    $y = printText( $text, $x, $y, $runLabel, $font->{Helvetica}{Bold}, 9 / pt );

    # Print the 'From: Payor' info
    #
    $y -= 9 / pt;

    my $supplierCode = $payor->SupplierCode();

    my $cityStateLine = $payor->City();
    if ( $payor->City() && $payor->StateProvince() ) {
        $cityStateLine .= ",";
    }
    $cityStateLine .= $payor->StateProvince() . " " . $payor->PostalCode();

    $y = printText( $text, $x, $y, 'From:',                 $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, $payor->Name(),          $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, $payor->StreetAddress(), $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, $cityStateLine,          $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, $payor->CountryCode(),   $font->{Helvetica}{Roman}, 9 / pt );

    my $reportingPeriod = "Q" . $run->Quarter() . " " . $run->Year();

    # Add in some details here
    $y -= 9 / pt;
    $y = printText( $text, $x, $y, "Account Number: $supplierCode",      $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "Reporting Period: $reportingPeriod", $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "Scheme Code: $mcpsScheme",           $font->{Helvetica}{Roman}, 9 / pt );

    # Add in some space, then print the 'To:' info
    #
    $y -= 9 / pt;

    $y = printText( $text, $x, $y, "Mechanical Copyright Protection Society Ltd ", $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "Elgar House",                                  $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "41 Streatham High Road",                       $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "London",                                       $font->{Helvetica}{Roman}, 9 / pt );
    $y = printText( $text, $x, $y, "SW161ER",                                      $font->{Helvetica}{Roman}, 9 / pt );

    $y -= 18 / pt;

    #
    # Add in Estimated Liability and Royalty Payable Units (FB12755)
    #
    my $statementRoyaltyPayableUnits = formatNumber( $statement->RoyaltyPayableUnits() );
    my $statementEstimatedLiability  = formatMoney( $statement->EstimatedLiability() );

    my $label1 = "Royalty Payable Units: ";
    $y = printText( $text, $x, $y, "$label1 $statementRoyaltyPayableUnits", $font->{Helvetica}{Bold}, 9 / pt );

    my $newX = $text->advancewidth($label1) + 2;
    my $newY = $y;

    $y = printText( $text, $x,         $newY, "Estimated Liability: ",        $font->{Helvetica}{Bold}, 9 / pt );
    $y = printText( $text, $x + $newX, $newY, "$statementEstimatedLiability", $font->{Helvetica}{Bold}, 9 / pt );

    return ( $x, $y, $page );
}

sub details {
    my ( $pdf, $statement, $x, $y, $page ) = @_;
    my $fontSize = 7 / pt;

    # !! Let's see how it works without doing this...
    # start details on a new page
    #$page = newPage($pdf);
    #$y    = kTopMargin - 10;

    # Let's fetch the list now so that we can avoid printing things out if there is nothing to report.
    #
    my $itemList = $statement->McpsStatementItemList()->getList();

    if ( @$itemList > 0 ) {

        my @rows;
        my @rowProps;

        # Set up the header
        # 17 columns...
        push @rows, [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ];
        push @rowProps, {

        };

        push @rows, [ '', '', '', '', '', '', '', '', '', 'Net', '', '', '', '', '', '', '' ];
        push @rowProps,
          {
            font       => $font->{Helvetica}{Bold},
            repeatRows => 1,
          };

        push @rows, [ '', '', '', 'Product', '', '', 'Prior', '', '', 'Royalty', '', 'TV', '', '', 'Price', '', '' ];
        push @rowProps,
          {
            font       => $font->{Helvetica}{Bold},
            repeatRows => 1,
          };

        push @rows,
          [
            'Album Title', 'Catalog #', 'MCPS ID', 'Format', 'Country',    'Gross',
            '(-)',         'Promo',     'Returns', 'Units',  'Retentions', 'Retentions',
            'Net',         'Price',     'Type',    'Adj?',   'Comments'
          ];
        push @rowProps, {
            font       => $font->{Helvetica}{Bold},
            repeatRows => 1,
            lines      => [ {
                    start_col => 0,
                    end_col   => 16,
                    top_pad   => 4,

                    # bottom_pad => 2,
                },
            ],
        };

        # Add the statement item details.
        #

        foreach my $item (@$itemList) {
            itemDetails( $item, \@rows, \@rowProps );
        }

        # Force the columns to be fixed width.
        #
        my @colProps = ( {
                # album title
                min_w => 1.1 / in,
                max_w => 1.1 / in,
                pad   => 0,
            },
            {
                # catalog number
                min_w => 0.75 / in,
                max_w => 0.75 / in,
                pad   => 0,
            },
            {
                # mcps id
                min_w => 0.7 / in,
                max_w => 0.7 / in,
                pad   => 0,
            },
            {
                # product format
                justify => 'center',
                min_w   => 0.4 / in,
                max_w   => 0.4 / in,
                pad     => 0,
            },
            {
                # country
                justify => 'center',
                min_w   => 0.45 / in,
                max_w   => 0.45 / in,
                pad     => 0,
            },
            {
                # gross units
                justify => 'right',
                min_w   => 0.55 / in,
                max_w   => 0.55 / in,
                pad     => 0,
            },
            {
                # prior (-)
                justify => 'right',
                min_w   => 0.5 / in,
                max_w   => 0.5 / in,
                pad     => 0,
            },
            {
                # promo units
                justify => 'right',
                min_w   => 0.5 / in,
                max_w   => 0.5 / in,
                pad     => 0,
            },
            {
                # returns (-)
                justify => 'right',
                min_w   => 0.5 / in,
                max_w   => 0.5 / in,
                pad     => 0,
            },
            {
                # net units
                justify => 'right',
                min_w   => 0.55 / in,
                max_w   => 0.55 / in,
                pad     => 0,
            },
            {
                # retentions (-)
                justify => 'right',
                min_w   => 0.6 / in,
                max_w   => 0.6 / in,
                pad     => 0,
            },
            {
                # tv retentions
                justify => 'right',
                min_w   => 0.6 / in,
                max_w   => 0.6 / in,
                pad     => 0,
            },
            {
                # final net units
                justify => 'right',
                min_w   => 0.5 / in,
                max_w   => 0.5 / in,
                pad     => 0,
            },
            {
                # price
                justify => 'right',
                min_w   => 0.4 / in,
                max_w   => 0.4 / in,
                pad     => 0,
            },
            {
                # price type
                justify => 'center',
                min_w   => 0.35 / in,
                max_w   => 0.35 / in,
                pad     => 0,
            },
            {
                # adjustment?
                justify => 'center',
                min_w   => 0.35 / in,
                max_w   => 0.35 / in,
                pad     => 0,
            },
            {
                # comments?
                min_w => 1.3 / in,
                max_w => 1.3 / in,
                pad   => 0,
            },
        );

        my $tableObj = TableObj->new(
            $pdf, $page, \@rows,
            bottom_margin => kBottomMargin + 20,          # adding a bit of padding to avoid weirdness
            new_page_y    => kTopMargin - 20,             # ditto
            new_page_func => \&newPage,
            font          => $font->{Helvetica}{Roman},
            font_size     => $fontSize,
            column_props  => \@colProps,
            row_props     => \@rowProps,
        );

        ( $page, $y ) = $tableObj->print( $x, $y );

        # Last, print the grand totals
        #
        my $statementNetUnits   = formatNumber( $statement->NetUnits() );
        my $statementGrossUnits = formatNumber( $statement->GrossUnits() );

        $y -= 5 / pt;

        my @totalRow;
        push @totalRow, [ 'Gross Units: ' . $statementGrossUnits, 'Net Units: ' . $statementNetUnits, ' ' ];

        my $table = TableObj->new(
            $pdf, $page, \@totalRow,
            bottom_margin => kBottomMargin + 20,         # adding a bit of padding to avoid weirdness
            new_page_y    => kTopMargin - 10,            # ditto
            new_page_func => \&newPage,
            font          => $font->{Helvetica}{Bold},
            font_size     => $fontSize,
            column_props  => [ {
                    justify => 'right',
                    min_w   => 3.95 / in,
                    max_w   => 3.95 / in,
                    pad     => 0,
                },
                {
                    justify => 'right',
                    min_w   => 3.75 / in,
                    max_w   => 3.75 / in,
                    pad     => 0,
                },
                {
                    justify => 'right',
                    min_w   => 2.3 / in,
                    max_w   => 2.3 / in,
                    pad     => 0,
                },
            ],
            row_props => [ {

                },
            ],
        );
        ( $page, $y ) = $table->print( $x, $y );
    }

    return ( $x, $y, $page );
}

sub itemDetails {
    my ( $item, $rows, $rowProps ) = @_;

    # Go through the entire mcps item list
    #

    my $adjusted;
    if ( $item->Adjustment() == 1 ) {
        $adjusted = 'Y';
    }

    my $catalogNumber = $item->CatalogNumber();
    # 288 = RSTestUK, 315 = VP Records UK, 443 = Jungle Records, 461 = The Orchard UK
    if ( Common::RSApp::GetClientID() =~ /^(288|315|443|461)$/ )
    {
        my $productCode = $item->ProductCode();
        $catalogNumber = $productCode if ($productCode);
    }

    # !!! We may have to truncate titles?
    # !!! Either that, or we implement some sort of cell wrapping.
    #
    push @$rows,
      [
        $item->AlbumTitle(),
        $catalogNumber,
        $item->McpsID(),
        productCodeToName( $item->ProductTypeID() ),
        $item->CountryCode(),
        formatNumber( $item->GrossUnits() ),
        formatNumber( $item->PriorUnits() ),
        formatNumber( $item->PromoUnits() ),
        formatNumber( $item->ReturnUnits() ),
        formatNumber( $item->NetUnits() ),
        formatNumber( $item->Retentions() ),
        formatNumber( $item->TVRetentions() ),
        formatNumber( $item->FinalNetUnits() ),
        formatMoney( $item->Price() ),
        $item->McpsPriceType(),
        $adjusted,
        $item->Comments(),
      ];

    push @$rowProps, {};

    # We want a little line under the last income item.
    #
    my $numRows = scalar(@$rowProps);
    my $lastRowPropHashref = $$rowProps[ ( $numRows - 1 ) ];
    $lastRowPropHashref->{lines} = [ {
            start_col => 0,
            end_col   => 16,
            top_pad   => 2,

            # bottom_pad => 2,
        },
    ];

}

sub addFooter {
    my ($pdf) = @_;

    my $pageCount = 1;
    my $numPages  = scalar @gPages;
    foreach my $page (@gPages) {
        my $text = $page->text;
        printTextCentered( $text, kBottomMargin, "$pageCount of $numPages", $font->{Helvetica}{Roman}, 12 / pt );
        $pageCount++;
    }
}

# All the pages will _probably_ need the same settings.
#
sub newPage {
    my ($pdf) = @_;

    my $page = $pdf->page;

    # the mediabox is the size of the paper.
    #
    $page->mediabox( kPageWidth, kPageHeight );

    # the cropbox defines the margins, essentially.
    # the args are the coordinates for the left, bottom, right, and top (in that order)
    #

    # !!! Rather than set the cropbox right to the margins, I am going to make it larger.
    # !!! Basically, I want to have this thing render in the viewer with the apperance of having
    # !!! margins.
    #
    #    $page->cropbox(kLeftMargin, kBottomMargin, kRightMargin, kTopMargin);
    $page->cropbox( 5, 5, kPageWidth - 5, kPageHeight - 5 );

    # Not currently declaring a 'bleedbox' or an 'artbox'.  Check out the tutorial if you want to
    # know what those are... the url for that is at the top of this file.
    #
    push @gPages, $page;

    return $page;
}

# A helper routine to print some text centered.
# 'y' will tell it where to start - 'x' is basically ignored.
#
sub printTextCentered {
    my ( $text, $y, $textToPrint, $fontToUse, $fontSize, $color ) = @_;

    $color = 'black' unless $color;

    $text->font( $fontToUse, $fontSize );
    $text->fillcolor($color);

    my @strings = split( /\n/, $textToPrint );
    foreach my $string (@strings) {

        # Remove any carriage returns that are left over from the new line splitting above.
        $string =~ s/\r//g;

        # Calculate how wide this string will be.
        #
        my $stringWidth = $text->advancewidth($string);

        $y -= $fontSize;

        # Calculate where 'X' needs to be
        #
        my $x = ( ( kRightMargin - kLeftMargin ) / 2 ) + kLeftMargin - ( $stringWidth / 2 );

        $text->translate( $x, $y );
        $text->text($string);

        # Move the cursor down the page.
        # add a little bitty bit of padding
        $y -= 1;
    }

    return $y;
}

# This just prints a line of text, left justified to the left margin
#
sub printText {
    my ( $text, $x, $y, $textToPrint, $fontToUse, $fontSize, $color ) = @_;

    $color = 'black' unless $color;

    $text->font( $fontToUse, $fontSize );
    $text->fillcolor($color);

    my @strings = split( /\n/, $textToPrint );
    foreach my $string (@strings) {

        # Remove any carriage returns that are left over from the new line splitting above.
        $string =~ s/\r//g;

        # Calculate how wide this string will be.
        #
        my $stringWidth = $text->advancewidth($string);

        $y -= $fontSize;

        $text->translate( $x, $y );
        $text->text($string);

        # Move the cursor down the page.
        # add a little bitty bit of padding
        $y -= 1;
    }

    return $y;
}

sub formatNumber {
    my ($value) = @_;

    $value = Formats::formatNumber($value);

    return $value;
}

sub formatMoney {
    my ($value) = @_;

    # Use our own rounding algorithm.
    #
    my $rVal = Common::RSMath::round( $value, 2 );

    $rVal = Common::Client::Current()->Locale()->formatMoney( $rVal, "GBP" );

    return $rVal;

    #my ($value) = @_;

    #$value = Formats::formatMoney($value);

    #return $value;
}

sub formatPercent {
    my ($value) = @_;

    $value = Formats::formatPercent($value);

    return $value;
}

sub formatDate {
    my ($value) = @_;

    $value = Formats::formatDate($value);

    return $value;
}

# These functions map ids to their text representations.
# Basically, the first time we ask for a particular id->string mapping, we
# will query the correct database, and build a hash.  Subsequent calls just
# hit the hash.
#
# Because these tables are so similar, I abstracted the guts into the _genericMapAccessor
# method (to save myself some typing).
#
my %idMaps;

sub _genericMapAccessor {
    my ( $collectionAccessor, $idName, $id ) = @_;

    if ( !defined $idMaps{$collectionAccessor} ) {
        $idMaps{$collectionAccessor} = {};

        # This is a very naughty thing to do, but it works great in this context.
        #
        #        no strict 'refs';
        #        my $c = &$collectionAccessor();
        #        use strict 'refs';
        my $c = $collectionAccessor->GetAll();

        while ( my $item = $c->next() ) {
            if ( $idName ne 'product_type_id' ) {
                $idMaps{$collectionAccessor}{ $item->$idName() } = $item->name;
            } else {
                $idMaps{$collectionAccessor}{ $item->$idName() } =
                  $item->description;
            }
        }
    }

    return $idMaps{$collectionAccessor}{$id};
}

sub incomeSourceIDToName {
    my ($id) = @_;

    return _genericMapAccessor( 'RPS::DB::Item::IncomeSource', 'income_source_id', $id );
}

sub regionIDToName {
    my ($id) = @_;

    # we don't want to show Rest of World here
    if ( $id != 0 ) {
        return _genericMapAccessor( 'RPS::DB::Item::Region', 'region_id', $id );
    } else {
        return ' ';
    }
}

sub channelIDToName {
    my ($id) = @_;
    return _genericMapAccessor( 'RPS::DB::Item::Channel', 'channel_id', $id );
}

sub priceLevelIDToName {
    my ($id) = @_;
    return _genericMapAccessor( 'RPS::DB::Item::PriceLevel', 'price_level_id', $id );
}

sub contractRateTypeIDToName {
    my ($id) = @_;
    return _genericMapAccessor( 'RPS::DB::Item::ContractRateType', 'contract_rate_type_id', $id );
}

sub productCodeToName {
    my ($id) = @_;
    return _genericMapAccessor( 'RPS::DB::Item::ProductType', 'product_type_id', $id );
}

sub addDraftWatermark {
    my ($pdf) = @_;

    my $centerX = kPageWidth / 2;
    my $centerY = kPageHeight / 2;

    foreach my $page (@gPages) {
        my $text = $page->text(1);
        $text->font( $font->{Helvetica}{Bold}, 128 / pt );
        $text->transform(
            -translate => [ $centerX, $centerY ],
            -rotate    => 45
        );

        $text->fillcolor('lightgray');
        $text->text_center('DRAFT');
        $text->fillcolor('black');
    }
}

#
# Boring script stuff below...
#

sub parseCommandLine {
    my ($settings) = @_;

    my %opt;
    getopts( 's:c:f:V:', \%opt );

    if ( !$opt{s} || !$opt{c} ) {
        usage();
        exit(1);
    }
    $settings->{mcpsStatementID} = $opt{s};
    $settings->{clientID}        = $opt{c};
    $settings->{outputPath}      = $opt{f};

    if ( defined $opt{V} ) {
        $gVerbosityLevel = $opt{V};
    }
}

sub usage {
    print STDERR "\nusage: $0 -c <client_id> -s <mechanical_statement_id> [-f <output path>]\n";
    print STDERR "\n";
    print STDERR "Arguments:\n";
    print STDERR "\t-c <client_id>\t\t\tThe client_id of the client to process\n";
    print STDERR "\t-s <mechanical_statement_id>\tThe id of the mcps statement to convert to pdf\n";
    print STDERR "\t-f <output path>\tThe output path. Optional. If not provided, we'll make one up\n";
}

sub report {
    my ( $string, $verbosity ) = @_;
    $verbosity = 1 unless defined $verbosity;

    if ( $gVerbosityLevel >= $verbosity ) {
        print STDERR $string . "\n";
    }
}

