#------------------------------------------------------------
# Copyright (C) 2008 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package MediaServe::Image::Command::Serve;
use strict;
use warnings;

use lib '/app/tools/mediaserve/lib';
use MediaServe::Command;
use MediaServe::Image::ImageFile;

use lib '/app/tools/common/lib';
use RSApache::DBSession;
use RSApache::Response::Code;
use RSApache::Response::Direct;
use Common::Log;

use base 'MediaServe::Command';

use constant kProcessingThumbnailPath => '/app/tools/common/production/images/image_processing_thumb.png';

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

    my $response = $self->SUPER::execute();
    return $response if $response;

    eval {
        # This command is not a 'sessioned' command  -  We don't check to
        # see whether the session id is valid.
        # However, we do want to know the id, since we use that as the key for the encoded url.
        #
        my $sessionID = RSApache::DBSession::GetSessionIDFromCookie();
        die "ERROR - no session" unless $sessionID;

        # We'll use an object.  What a surprise!
        #

        # The 'token' is the last chunk in the path
        #
        my $url = $ENV{REQUEST_URI};
        my ( $path, $args ) = split( '\?', $url );
        my @bits = split( '\/', $path );
        my $token = $bits[ ( scalar @bits ) - 1 ];

        my $imageObj = MediaServe::Image::ImageFile->new( token => $token );
        die "ERROR - no image obj" unless $imageObj;

        # Does the sesssion match?
        #
        if ( $sessionID != $imageObj->sessionID() ) {
            die "ERROR - invalid session id";
        }

        # See if this image has expired.
        #
        my $now          = time();
        my $timeToExpire = $imageObj->expirationDate();
        if ( $now >= $timeToExpire ) {
            die "ERROR - image has expired";
        }

        # Serve the file if it exists.
        # If it doesn't exist, serve some sort of placeholder image.
        #
        my $pathToFile = $imageObj->logicalVolume() . '/' . $imageObj->relativePath() . '/' . $imageObj->id();
        Common::Log::Debug("IMAGE PATH OUGHT TO BE: $pathToFile");
        if ( !-e $pathToFile ) {
            $pathToFile = kProcessingThumbnailPath;
        }

        Common::Log::Debug("SERVING IMAGE AT PATH: $pathToFile");
        open( FD, "$pathToFile" ) or die "ERROR - cannot open file $pathToFile for reading";

        $response = RSApache::Response::Direct->new( *FD, $imageObj->fileType() );
    };
    if ($@) {
        print STDERR "CAUGHT AN EXCEPTION: $@\n";
        $response = RSApache::Response::Code->new(404);
    }

    return $response;
}

1;
