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

use lib '/app/tools/mediaserve/lib';
use MediaServe::Command;
use MediaServe::Audio::AudioFile;
use MediaServe::DB::Item::ProductTrackFile;

# We have to lard this up now just to generate a filename...
#
use lib '/app/tools/rps/lib';
use RPS::DB::Item::ProductTrack;
use RPS::DB::Item::Artist;
use RPS::DB::Item::Album;
use RPS::DB::Item::Product;

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

use base 'MediaServe::Command';

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 $audioObj = MediaServe::Audio::AudioFile->new( token => $token );
        die "ERROR - no audio obj" unless $audioObj;

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

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

        # Serve the file if it exists.
        # !!! Not quite certain how to handle non-existent files.
        #
        my $pathToFile = $audioObj->logicalVolume() . '/' . $audioObj->relativePath() . '/' . $audioObj->id();

        if ( !-e $pathToFile ) {
            die "ERROR : no file at path $pathToFile";
        }

        # Determine the size of the flac file
        #
        my $fileSize = int( ( -s $pathToFile ) * 0.21 );

        my $cmd = "/usr/bin/flac -sdc $pathToFile | /usr/bin/lame -S - - ";

        Common::Log::Debug("SERVING AUDIO WITH CMD: $cmd");
        open( FD, "$cmd |" ) or die "ERROR - cannot open pipe to command $cmd : $!";

        my $mediaID = $audioObj->id();
        my $productTrackFile = MediaServe::DB::Item::ProductTrackFile->Lookup( media_file_id => $mediaID );
        die "ERROR - no product track file associated with media file id $mediaID" unless $productTrackFile;

        my $productTrack = RPS::DB::Item::ProductTrack->Lookup( product_track_id => $productTrackFile->product_track_id );
        my $trackID      = $productTrack->track_id;
        my $track        = RPS::DB::Item::Track->Lookup( track_id => $trackID );
        my $album        = RPS::DB::Item::Album->Lookup( album_id => $track->album_id );
        my $artist       = RPS::DB::Item::Artist->Lookup( artist_id => $track->artist_id );

        my $filename =
          $artist->name_clean . '-' . $album->title_clean . '-' . $productTrack->disc_number . '-' . $productTrack->disc_track . '.mp3';
        Common::Log::Debug("Serving media id $mediaID with filename $filename");

        # !!! We need a mechanism to produce the correct filename, whatever that might be.
        #
        $response = RSApache::Response::Download->new( *FD, $audioObj->fileType(), $filename, $fileSize );
    };
    if ($@) {
        print STDERR "CAUGHT AN EXCEPTION: $@\n";
        $response = RSApache::Response::Code->new(404);
    }

    return $response;
}

1;
