use strict;

FillInParentProductID->start();

package FillInParentProductID;
use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';

use Common::Log;
use Common::Util;
use Common::Client;
use Common::RSApp;
use RPS::DB::Item::Product;
use RPS::DB::Item::Track;

use base 'RPS::Script';

sub _options {
    {
        test => {
            short       => 't',
            description => 'Test only, no changes',
            required    => 0,
        },
        alter => {
            short       => 'a',
            description => 'Alter database (add new column)',
            required    => 0,
        },
    };
}

sub _process {
    my $self = shift;

    my $clientName = Common::Client::Current()->ClientName();
    print "$clientName\n";

    if ( $self->{_test} ) {
        print "Running in test mode.  No changes will be saved.\n";
    }

    my $dbo = Common::RSApp::GetClientDB();

    # First we need to add the new column.
    if ( !$self->{_test} && $self->{_alter} ) {
        $dbo->DoCmd('ALTER TABLE product ADD COLUMN parent_product_id int(10) unsigned default NULL AFTER product_id');
    }

    # Now we can fill it in for the digital track products.
    my $products = RPS::DB::Item::Product->GetAll();

    while ( my $product = $products->next() ) {
        if ( $product->product_type_id != RPS::DB::Item::Product::kProductTypeDigitalTrack ) {
            next();
        }

        # Skip if we've already populated parent_product_id
        if ( $product->parent_product_id ) {
            next();
        }

        my $track = RPS::DB::Item::Track->Lookup( track_id => $product->asset_id );

        if ($track) {
            my $albumProducts = RPS::DB::Item::Product->GetAllDigitalAlbumProducts( $track->album_id );

            if ( $albumProducts->size() == 1 ) {
                if ( !$self->{_test} ) {
                    my $albumProduct = $albumProducts->next();
                    $product->parent_product_id( $albumProduct->product_id );
                    $product->save();
                }
            } elsif ( $albumProducts->size() == 0 ) {
                Log->warn( "Unable to find parent product for product ID: " . $product->product_id );
            } else {
                Log->warn( "Found multiple parent products for product ID: " . $product->product_id );
            }
        }
    }

}

sub _getProductionClientIDs {
    return Common::RSDB::GetAllRPSClientIDs();
}

sub _getLocalClientIDs {
    return 202;    # RS Test
}

1;
