#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::DB::Item::ChapterContributor;

use strict;
use warnings;

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

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::ContributorRole;

use constant kTable => 'chapter_contributor';
use constant kDB    => Common::DB::Item::kClientDB;

sub GetAllByChapterID {
    my ( $class, $chapterID ) = @_;
    assert($chapterID);

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

sub GetAuthorNamesByChapterID {
    my ( $class, $chapterID ) = @_;
    return $class->_getAuthorsByChapterID( $chapterID, 'name_inverted' );
}

sub GetAuthorLastNamesByChapterID {
    my ( $class, $chapterID ) = @_;
    return $class->_getAuthorsByChapterID( $chapterID, 'last_name' );
}

sub _getAuthorsByChapterID {
    my ( $class, $chapterID, $nameChoice ) = @_;
    my $dbo = Common::RSApp::GetClientDB();
    my $sql =
        "SELECT contributor.$nameChoice as auth_name FROM contributor"
      . " LEFT JOIN chapter_contributor ON contributor.contributor_id = chapter_contributor.contributor_id"
      . " WHERE chapter_contributor.chapter_id=$chapterID"
      . " AND chapter_contributor.contributor_role_id="
      . BookPub::DB::Item::ContributorRole::kRoleIDAuthor
      . " ORDER BY auth_name";

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

    while ( my $hr = $sth->fetchrow_hashref() ) {
        push @names, $hr->{auth_name};
    }

    return wantarray ? @names : join( ', ', @names );
}

1;
