#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::XMLCache;

use strict;
use warnings;
use Carp;
use File::Path;

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

#use constant kBasePath => '/tmp/XMLCache/';
use constant kBasePath => '/app/data/XMLCache/';

# This class is _sorta_ like XMLObject, in that it provides a writeXML method.
# It provides a way to cache XML in a file to be retrieved later.
#

sub Fetch {
    my (@keys) = @_;

    my $cachePath = _getPath(@keys);

    # Look for the compressed version first, then the compressed, then give up.
    #
    if ( -e "$cachePath.gz" ) {
        if ( !open( CACHEFILE, "/bin/zcat $cachePath.gz |" ) ) {
            confess "unable to open $cachePath (compressed) for reading: $!\n";
        }
    } elsif ( -e $cachePath ) {
        if ( !open( CACHEFILE, $cachePath ) ) {
            confess "unable to open $cachePath for reading: $!\n";
        }
    } else {
        return undef;
    }

    my $text;
    while ( my $line = <CACHEFILE> ) {
        chomp $line;

        # This is a bit of a hack... the WriteXML mechanism insists
        # on wrapping <Root> tags around everything.  We don't want that.
        #
        next if ( $line eq '<Root>' || $line eq '</Root>' );

        $text .= $line . "\n";
    }
    close(CACHEFILE);

    my $obj = RPS::XMLCache->new($text);
    return $obj;
}

sub OLD_Store {
    my ( $data, @keys ) = @_;

    my $cachePath = _getPath(@keys);

    my $text = Common::WriteXML::GetXMLString($data);

    if ( !open( CACHEFILE, "> $cachePath" ) ) {
        confess "unable to open $cachePath for writing: $!\n";
    }
    print CACHEFILE $text;

    close(CACHEFILE);
}

sub Store {
    my ( $data, @keys ) = @_;

    my $cachePath = _getPath(@keys);

    Common::WriteXML::WriteXMLFile( $data, $cachePath );

    # !!! gzip the file afterwards
    #
    if ( -e $cachePath ) {
        system("/bin/gzip $cachePath");
    }

    #    if (! open(CACHEFILE, "> $cachePath"))
    #    {
    #        confess "unable to open $cachePath for writing: $!\n";
    #    }
    #    print CACHEFILE $text;
    #
    #    close(CACHEFILE);
}

sub new {
    my ( $class, $text ) = @_;

    my $self = bless {}, $class;
    $self->{_text} = $text;

    return $self;
}

sub writeXML {
    my ( $self, $xw, $tag ) = @_;

    $xw->element_raw( $tag, $self->{_text} );
}

sub _getPath {
    my (@keys) = @_;

    my $filename = pop(@keys);
    assert($filename);

    my $path = kBasePath;

    # We may have multiple clients per host, which will almost certainly
    # lead to id space collision.
    #
    my $clientID = Common::RSApp::GetClientID();
    $path .= "$clientID/";

    $path .= join( '/', @keys );

    mkpath($path);

    $path .= "/$filename";

    return $path;
}

1;
