#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Distribution::UpdateNotification;
use strict;
use warnings;

use Sys::Hostname;

use lib '/app/tools/common/lib';
use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::WriteXML;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Album;

use lib '/app/tools/distribution/lib';
use Distribution::MetadataUpdate;

use base 'Common::CronScript';

sub run_process {
    my $self = shift;
    my @list = $self->_get_client_list();

    $self->debug("\nStarting update notification process");

    $self->debug("  Client list: @list");

    foreach (@list) {
        $self->_process_client($_);
    }
}

sub _process_client {
    my $self      = shift;
    my $client_id = shift;

    assert($self);
    assert($client_id);

    $self->debug("\n**** Starting process for client id: $client_id\n");

    my $singleton = new Common::RSApp( clientID => $client_id );
    die("Invalid client id '$client_id'")
      unless ( $singleton && Common::RSDB::ClientIDToDBName($client_id) );

    $self->_process($client_id);

    $singleton = undef;
}

sub _process() {
    my $self      = shift;
    my $client_id = shift;

    assert($client_id);

    my $update = new Distribution::MetadataUpdate( client_id => $client_id );
    my $update_report = $update->getUpdateReport;

    $self->_display_report( $client_id, $update_report );
}

sub _display_report {
    my $self        = shift;
    my $client_id   = shift;
    my $report_hash = shift;
    my ( $action, $album_id );

    assert($self);
    assert($client_id);

    return unless ($report_hash);

    my $client_db = Common::RSDB::ClientIDToDBName($client_id);
    my $album;
    my $product;

    print "Run on host: " . hostname . "\n\n";

    print "Metadata updates for client id: $client_id (DB: $client_db)\n";

    use Data::Dumper;
    Common::Log::Debug( Dumper($report_hash) );

    foreach $album_id ( keys(%$report_hash) ) {
        $album = RPS::DB::Item::Album->Lookup( album_id => $album_id );
        $product = RPS::DB::Item::Product->Lookup( asset_id => $album_id, product_type_id => RPS::DB::Item::Product::kProductTypeDigital );

        printf( "  Album ID: %s, Title: %s, UPC: %s\n", $album_id, $album->title, $product ? $product->upc_ean : "" );

        foreach $action ( sort keys( %{ $report_hash->{$album_id} } ) ) {
            print "\n    ACTION: $action\n";
            foreach ( @{ $report_hash->{$album_id}->{$action} } ) {
                print "      $_->{table} => $_->{data}\n";
            }
        }
    }

    print "\n\n";
}

1;
