#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::DB::MetadataItem;

use strict;
use warnings;
use Data::Dumper;
use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::RSApp;
use Common::Assert;
use Common::Log;
use Common::DB::Item;
use base 'Common::DB::ItemWithHistory';

use Data::Dumper;

# This class is to be used as the baseclass for the BookPub metadata tables.
# It does two things:
# - It inherits from Common::DB::ItemWithHistory, so we'll be able to keep historical data around.
# - It automagically populates the 'catalog_import_id' column, similar to how the base Common::DB::Item
#   class populates 'modified_by'.  This will allow us to track changes to metadata back to the original
#   import 'event', or to the user that manually made the change.

# !!! So, I want to record the catalog_import_id (if set in the singleton) when we're doing either
# !!! an insert or an update.

sub _create {
    my ($self) = @_;

    if ( !$self->catalog_import_id() ) {
        $self->catalog_import_id( $self->_getCatalogImportID() );
    }

    return $self->SUPER::_create();
}

sub _update {
    my ($self) = @_;

    # We don't want to set the catalog_import_id UNLESS:
    # - Some other field was also changed (i.e. the object is 'dirty')
    # - The catalog_import_id was not explicitly changed already.
    #
    my $globalCatalogImportID = $self->_getCatalogImportID();
    if ( $self->isDirty() && !$self->{_dirty}{catalog_import_id} && $globalCatalogImportID ) {
        $self->catalog_import_id($globalCatalogImportID);
    }

    return $self->SUPER::_update();
}

sub _getCatalogImportID {
    my ($self) = @_;

    # Get the catalog_import_id out of the application's ram cache.
    # In order for that to _be_ there, we'll have to have explicitly
    # PUT it there.
    # Currently, we are doing that in the BookPub::Catalog::Import::Process classes, in
    # their 'run()' method.
    #
    return Common::RSApp::GetRAMCache()->{catalogImportID};
}

1;
