<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class IndexAction extends AuthorAction
{
    public function run()
    {
        $bookId = S::gp('bid','G',2);
        $book = $this->isBookOwner($bookId);
        
        $isWebRequest = $this->getController()->isWebRequest();
        $order = ' sort DESC';
        if ($isWebRequest)
        {
            $order = ' sort ASC';
            $limit = '';
        }
        else
        {
            $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Chapter::table().' WHERE bookid='.S::sqlEscape($bookId));
            $pageObj = new iPage();
            $pageObj->setPageSize(10);
            $pageObj->setTotalRecord($count);
            $limit = ' LIMIT '.$pageObj->getOffset().','.$pageObj->getPageSize();
        }
        $sql = 'SELECT c.*,dc.year,dc.month,dc.day,dc.hour FROM '.Chapter::table().' AS c LEFT JOIN '.DraftCron::table().' AS dc ON dc.cid = c.chapterid WHERE bookid='.S::sqlEscape($bookId).' ORDER BY '.$order.$limit;
        $chapters = $this->db()->setQueryString($sql)->find();
        if (!empty($chapters))
        {
            foreach ($chapters as &$chapter)
            {
                $chapter['cron'] = !empty($chapter['year']) ? DraftCron::single()->isValid(array('year' => $chapter['year'], 'month' => $chapter['month'], 'day' => $chapter['day'], 'hour' => $chapter['hour'])) : false;
            }
        }

        $this->getController()->render('index', array(
                'book' => $book,
                'chapters' => $chapters,
                'pageObj' => $pageObj,
            )
        );
    }
}