#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::DB::Item::ProductTrack;
use strict;
use warnings;
use lib '/app/tools/common/lib';
use Common::Assert;
use Common::DB::Item;
use Common::DB::ItemCollection;
use base 'Common::DB::Item';

use constant kTable => 'product_track';
use constant kDB    => Common::DB::Item::kClientDB();

sub GetTracksByProductID {
    my ( $class, $productID ) = @_;

    my $sql = "SELECT * FROM " . kTable . " WHERE product_id=$productID ORDER BY disc_number, disc_track";
    Common::Log::Debug("QUERY: $sql");
    return $class->GetAll($sql);
}

sub GetByTrackID {
    my ( $class, $trackID ) = @_;

    my $sql = "SELECT * FROM " . kTable . " WHERE track_id=$trackID";
    return $class->GetAll($sql);
}

sub TrackIsBonusTrack {
    my ( $class, $trackID ) = @_;

    my $sql = "SELECT COUNT(*) from " . kTable . " WHERE track_id=$trackID AND is_bonus_track=1";

    my $dbo = Common::RSApp::GetClientDB();

    my $sth = $dbo->DoCmd($sql);

    my $aref = $sth->fetchrow() if ($sth);

    return ( defined $aref ) ? $aref : 0;
}

sub GetNextDiscNumAndDiscTrack {
    my ( $class, $productID ) = @_;

    my $dbo = Common::RSApp::GetClientDB();

    # We'll get the highest disc number first, then figure out what the next track on
    # that disc would be.
    #
    my $sth = $dbo->DoCmd( "SELECT MAX(disc_number) FROM " . kTable . " WHERE product_id=$productID" );
    my ($nextDiscNum) = $sth->fetchrow_array();
    if ( !$nextDiscNum ) {
        return ( 1, 1 );
    }

    $sth = $dbo->DoCmd( "SELECT MAX(disc_track) FROM " . kTable . " WHERE product_id=$productID AND disc_number=$nextDiscNum" );
    my ($nextDiscTrack) = $sth->fetchrow_array();
    $nextDiscTrack++;

    return ( $nextDiscNum, $nextDiscTrack );
}

1;
