#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::DB::Item::ProductDigital;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::DB::Item;
use Common::Timer;
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Product;

use base 'Common::DB::Item';

use constant kTerritoriesFlagAllow => 'A';
use constant kTerritoriesFlagDeny  => 'D';

use constant kDistAllowYes => 1;
use constant kDistAllowNo  => 0;

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

sub GetByProductID {
    my $productID = shift;
    my $t         = Common::Timer->new();

    my $sql = "SELECT * FROM " . kTable . " WHERE product_id = ?";

    my $collection = Common::DB::ItemCollection->new(
        class        => "RPS::DB::Item::ProductDigital",
        query        => $sql,
        dbID         => kDB,
        placeHolders => [$productID],
    );

    return $collection;
}

sub GetByAlbumID {
    my $class   = shift;
    my $albumID = shift;
    my $t       = Common::Timer->new();
    my $dbo     = Common::RSApp->GetClientDB();

    my $sql =
        "SELECT product.product_id, territories_list, territories_flag, dist_allow FROM product "
      . "LEFT JOIN "
      . kTable
      . " as pd USING (product_id) "
      . "INNER JOIN album ON (asset_id = album_id AND product_type_id = 3) "
      . "WHERE album_id = "
      . $dbo->DBQuote($albumID);

    Common::Log::Debug("QUERY: $sql");
    my $collection = Common::DB::ItemCollection->new(
        class => "RPS::DB::Item::ProductDigital",
        query => $sql,
        dbID  => kDB
    );

    return $collection;
}

sub GetAll {
    my $sql = "SELECT * from " . kTable;
    my $t   = Common::Timer->new();

    my $collection = Common::DB::ItemCollection->new(
        class => "RPS::DB::Item::ProductDigital",
        query => $sql,
        dbID  => kDB
    );

    return $collection;
}

sub GetAllWithoutAssets {
    my ( $class, %args ) = @_;
    my $type = $args{type};

    assert($type);

    my $sql =
        "SELECT * from "
      . kTable
      . " LEFT JOIN product USING (product_id) "
      . "WHERE product_type_id = "
      . RPS::DB::Item::Product::kProductTypeDigital;

    if ( $type eq 'audio' ) {
        $sql .= " AND audio_id IS NULL ";
    } elsif ( $type eq 'image' ) {
        $sql .= " AND image_id IS NULL ";
    } else {
        die "Unknown asset type '$type'";
    }

    Common::Log::Debug("QUERY: $sql");
    return $class->SUPER::GetAll($sql);
}

1;
