#------------------------------------------------------------
# Copyright (C) 2007 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::Item::MechanicalRunTrackLicense;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Util qw(escape_mysql_regexp escape_mysql_like);
use Common::DB::ItemCollection;
use Common::Assert;
use Common::RSApp;

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

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

# !!! For the 'run_type' column, use the constants from SaleRunMap for now
sub GetByRunIDAndTypeAndCountryCode
{
    my ($class, $id, $type, $countryCode) = @_;
    assert($id);
    assert($type);
    assert($countryCode);

    $type = $class->quote($type);
    $countryCode = $class->quote($countryCode);

    my $sql = "SELECT * FROM " . kTable . " WHERE run_id=$id AND run_type=$type and country_code=$countryCode";
    return $class->SUPER::GetAll($sql);
}

sub GetByRunIDAndType
{
    my ($class, $id, $type) = @_;
    assert($id);
    assert($type);

    my $sql = "SELECT * FROM " . kTable . " WHERE run_id=$id AND run_type='$type'";
    return $class->SUPER::GetAll($sql);
}

sub DeleteByRunIDAndType
{
    my ($class, $id, $type) = @_;
    assert($id);
    assert($type);

    my $sql = "DELETE FROM " . kTable . " WHERE run_id=$id AND run_type='$type'";
    my $dbo = Common::RSApp::GetClientDB();
    $dbo->DoCmd($sql);
}

sub updateUnits
{
    my $class = shift;
    my %args = @_;
    
    my $dbo = Common::RSApp::GetClientDB();
    
    my $sql = "INSERT INTO " . kTable .
              " ( run_id, run_type, track_license_id, product_id, track_id, base_rate, share, units, country_code, year ) " .
              " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " .
              "ON DUPLICATE KEY UPDATE units = units + ? ";
              
    $dbo->DoCmdWithPlaceholders( $sql,
                 [ $args{run_id}, $args{run_type}, $args{track_license_id}, $args{product_id},
                   $args{track_id}, $args{base_rate}, $args{share}, $args{units}, $args{country_code},
                   $args{year}, $args{units} ]
                   )
    || die "Failed update";
}

1;

