<?php
/**
 * COPS (Calibre OPDS PHP Server) class file
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Sébastien Lucas <sebastien@slucas.fr>
 */

require_once('base.php');

class Author extends Base {
    const ALL_AUTHORS_ID = "calibre:authors";
    
    const AUTHOR_COLUMNS = "authors.id as id, authors.name as name, authors.sort as sort, link.count as count";
    const SQL_AUTHORS_BY_FIRST_LETTER = "select {0} from authors, (select author,count(*) as count from books_authors_link group by author) link where link.author = authors.id and authors.sort like ? order by authors.sort";
    const SQL_ALL_AUTHORS = "select {0} from authors, (select author,count(*) as count from books_authors_link group by author) link where link.author = authors.id order by authors.sort ";
    
    public $id;
    public $name;
    public $sort;
    
    public function __construct($pid, $pname) {
        $this->id = $pid;
        $this->name = $pname;
    }
    
    public function getUri () {
        return "?page=".parent::PAGE_AUTHOR_DETAIL."&id=$this->id";
    }
    
    public function getEntryId () {
        return self::ALL_AUTHORS_ID.":".$this->id;
    }
    
    public static function getEntryIdByLetter ($startingLetter) {
        return self::ALL_AUTHORS_ID.":letter:".$startingLetter;
    }

    public static function getCount() {
        $nAuthors = parent::getDb ()->query('select count(*) from authors')->fetchColumn(0);
        $entry = new Entry (localize("authors.title"), self::ALL_AUTHORS_ID, 
            str_format (localize("authors.alphabetical", $nAuthors), $nAuthors), "text", 
            array ( new LinkNavigation ("?page=".parent::PAGE_AUTHORS_FIRST_LETTER)));
        return $entry;
    }
    
    public static function getAuthorsByFirstLetter($letter) {
        if (!$letter) { $letter = ""; }
        $len = mb_strlen($letter,'UTF-8')+1;
        $result = parent::getDb ()->query('select substring(sort, 1, '.$len.') as title, count(distinct sort) sort_cnt,count(*) as count,min(id) min_id,min(sort) min_sort
from authors
where sort like "'.$letter.'%"
group by substring(sort, 1, '.$len.')
order by substring(sort, 1, '.$len.')');
        $entryArray = array();
        while ($post = $result->fetchObject ())
        {
            if ($post->count==1) {
              $author = new Author ($post->min_id, $post->min_sort);
              $title = $post->min_sort;
              $entryid = $author->getEntryId();
              $link = array ( new LinkNavigation ($author->getUri ()));
            } elseif ($post->count > parent::maxItemsPerPage() && $post->sort_cnt>1) {
              $page = parent::PAGE_AUTHORS_FIRST_LETTER;
              $title= $post->title.'...';
              $entryid = Author::getEntryIdByLetter ($post->title);
              $link = array ( new LinkNavigation ("?page=".$page."&id=". rawurlencode ($post->title)));
            } else {
              $page = parent::PAGE_AUTHORS_STARTING_LETTERS;
              $title = $post->title.'...';
              $entryid = Author::getEntryIdByLetter ($post->title);
              $link = array ( new LinkNavigation ("?page=".$page."&id=". rawurlencode ($post->title)));            
            }
            array_push ($entryArray, new Entry ($title, $entryid, 
                str_format (localize("authorword", $post->count), $post->count), "text", 
                $link));
        }
        return $entryArray;
    }

    
    public static function getAuthorsByStartingLetter($letter) {
        return self::getEntryArray (self::SQL_AUTHORS_BY_FIRST_LETTER, array ($letter . "%"));
    }
    
    public static function getAllAuthors() {
        return self::getEntryArray (self::SQL_ALL_AUTHORS, array ());
    }
    
    public static function getEntryArray ($query, $params) {
        list ($totalNumber, $result) = parent::executeQuery ($query, self::AUTHOR_COLUMNS, "", $params, -1);
        $entryArray = array();
        while ($post = $result->fetchObject ())
        {
            $author = new Author ($post->id, $post->sort);
            array_push ($entryArray, new Entry ($post->sort, $author->getEntryId (), 
                str_format (localize("bookword", $post->count), $post->count), "text", 
                array ( new LinkNavigation ($author->getUri ()))));
        }
        return $entryArray;
    }
        
    public static function getAuthorById ($authorId) {
        $result = parent::getDb ()->prepare('select sort from authors where id = ?');
        $result->execute (array ($authorId));
        return new Author ($authorId, $result->fetchColumn (0));
    }
    
    public static function getAuthorByBookId ($bookId) {
        $result = parent::getDb ()->prepare('select authors.id as id, authors.sort as sort
from authors, books_authors_link
where author = authors.id
and book = ?');
        $result->execute (array ($bookId));
        $authorArray = array ();
        while ($post = $result->fetchObject ()) {
            array_push ($authorArray, new Author ($post->id, $post->sort));
        }
        return $authorArray;
    }
}