#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::Catalog::DistributionCache;

use strict;
use warnings;

use Time::HiRes qw( sleep );

use lib '/app/tools/common/lib';
use Common::Assert;
use Data::Dumper;

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

use base 'Common::FormObject';

sub _init {
    my ( $self, %args ) = @_;

    $self->SUPER::_init(%args);

    return $self;
}

sub jsonProgress {
    my $self = shift;
    assert($self);

    my ( $progress, undef, undef, $idle ) = RPS::DB::Item::AlbumDistributionReady->GetCacheProgress();
    my $remaining;

    my $result = sprintf( "'progress': %.2f, 'idle': %d", $progress * 100, $idle ) if ($progress);

    #my $result = sprintf( "'progress': %.2f", $progress ) if( $progress );

    return $result ? "{ $result }" : "{}";
}

sub refreshCache {
    my $self = shift;
    assert($self);
    my ($progress) = RPS::DB::Item::AlbumDistributionReady->GetCacheProgress();
    my $new_progress;

    # Don't run if another cache process is already running
    return "RUNNING" if ( $self->cacheProcessRunning() );

    # Clear the current cache and re-run
    RPS::DB::Item::AlbumDistributionReady->ClearInvalidCache();

    my $collection = RPS::DB::Item::Album->GetAllNoDistributionCache();

    my @ids;
    my $harness = new Metadata::Validate::Harness( failState => Validate::kStatusOK, ignoreCurrentData => 1 );

    # Check all albums to see if they are ready for distribution.  Then store the
    # Album ID to do a lookup later.
    while ( $collection->hasNext() ) {
        my $album = new RPS::Catalog::Album( _dbItem => $collection->next );
        $self->refreshAlbumStatus( album => $album, harness => $harness );
    }

    return "OK";
}

sub getAlbumStatus {
    my $self    = shift;
    my %args    = @_;
    my $album   = $args{album};
    my $albumID = $album ? $album->AlbumID : $args{albumID};

    assert($albumID);

    Common::Log::Debug("- Check to see if album status is dirty");
    my $dirty = RPS::DB::Item::AlbumDistributionReady->CacheRecordDirty( album_id => $albumID );
    my $status = RPS::DB::Item::AlbumDistributionReady->Lookup( album_id => $album->AlbumID );
    Common::Log::Debug("+ Dirty status: $dirty");

    $album = new RPS::Catalog::Album( albumID => $albumID ) unless ($album);

    # refresh if we are dirty or have no status
    $self->refreshAlbumStatus( album => $album ) if ( $dirty || !$status );

    return RPS::DB::Item::AlbumDistributionReady->Lookup( album_id => $album->AlbumID );
}

sub clearAlbumStatus {
    my $self     = shift;
    my %args     = @_;
    my $album    = $args{album};
    my $album_id = $album ? $album->AlbumID : $args{albumID};

    Common::Log::Debug("- Clear album status");

    assert($album_id);

    # Delete the old record so we can ensure a change is made and the mod_time is updated.
    my $daReady = RPS::DB::Item::AlbumDistributionReady->Delete( album_id => $album_id );
}

sub refreshAlbumStatus {
    my $self    = shift;
    my %args    = @_;
    my $album   = $args{album};
    my $harness = $args{harness}
      || new Metadata::Validate::Harness( failState => Validate::kStatusOK, ignoreCurrentData => 1 );

    Common::Log::Debug("- Refreshing album status");

    # Delete the old record so we can ensure a change is made and the mod_time is updated.
    my $daReady = RPS::DB::Item::AlbumDistributionReady->Delete( album_id => $album->AlbumID );
    $daReady = RPS::DB::Item::AlbumDistributionReady->Create();

    $daReady->album_id( $album->AlbumID );
    $daReady->metadata_valid( $album->validateMetadata( harness => $harness ) );
    $daReady->audio_valid( $album->validateAlbumAudio() );
    $daReady->image_valid( $album->validateAlbumImage() );

    $daReady->save();
}

sub cacheProcessRunning {
    my $self = shift;
    assert $self;

    my ( $progress, $cached, $current_cached );

    return RPS::DB::Item::AlbumDistributionReady->hasUpdate("15 second");
}

sub _clearInvalidAssetCache {
    my $self = shift;
    my $invalid;

    my $collection = RPS::DB::Item::Album->GetAllWithInvalidAssets();

    while ( $collection->hasNext() ) {
        my $album = new RPS::Catalog::Album( _dbItem => $collection->next );
        my $daReady = RPS::DB::Item::AlbumDistributionReady->Lookup( album_id => $album->AlbumID );

        if ($daReady) {
            if ( !$daReady->audio_valid() && $album->validateAlbumAudio() && $album->validateAudioAssets() ) {
                $daReady->delete();
                $daReady->save();
                $invalid = 1;
            }

            if ( !$daReady->image_valid() && $album->validateAlbumImage() && $album->validateImageAssets() ) {
                $daReady->delete();
                $daReady->save();
                $invalid = 1;
            }
        }
    }

    return $invalid;
}

sub cacheValid {
    my $self = shift;
    assert $self;

    my $dirty = RPS::DB::Item::AlbumDistributionReady->CacheRecordDirty();
    my ($progress) = RPS::DB::Item::AlbumDistributionReady->GetCacheProgress();

    return !( $dirty || $progress < 1 );
}

###
1;    #
###
