<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class SendAction extends DownloadAction
{
    public function run()
    {
        require_once ROOT_PATH . 'include/BookDowload.class.php';
        isLogin();
        $type = S::gp('type', 'G');
        $bookId = S::gp('bid', 'G', 2);
        $action = empty($_GET['action']) ? 'full' : S::gp('action');
        if (empty($type))
        {
            throw new iSystemException('非法操作');
        }

        $book = $this->db()->select(array('bookname','typeid','bookid'))->from(Book::table())->where(array('bookid'=>$bookId))->find(true);
        $check = $this->db()->getValue('SELECT COUNT(*) FROM `'.Order::table().'` WHERE `memberid` = '.$this->uid().' AND `id` = '.$bookId." AND `type` = 'book'");
        if (!$check)
        {
            $this->getController()->render('order', array('book'=>$book));
            exit();
        }

        if ($action == 'full')
        {
            $limit = '';
        }
        else
        {
            switch ($action)
            {
                case 'small':
                    $size = 50;
                    break;
                case 'big':
                    $size = 100;
                    break;
            }
            $num = S::gp('num', 'G', 2);
            $offset = ($num - 1) * $size;
            $limit = " LIMIT $offset,$size";
        }
        $bookinfo = array('bid' => $bookId, 'bookname' => $book['bookname']);
        $class = 'iOrange' . $type;
        try
        {
            $downloader = new $class($bookinfo);
        }
        catch (Exception $e)
        {
            throw new iSystemException("Faild Object");
        }
        $sql = "SELECT `chapterid`, `chaptername` FROM `".Chapter::table()."` WHERE `bookid` = '{$bookId}' AND isimage = 0 AND display = 1 ORDER BY `sort` ASC $limit";
        $query = $this->db()->query($sql);
        ini_set('memory_limit', '20M');
        while ($row = $this->db()->getArr($query))
        {
            $downloader->addChapter($row['chaptername'], Chapter::getContent($bookId, $row['chapterid']));
        }

        $downloader->download();
        $uid = $this->uid();
        $this->db()->query("INSERT INTO `".Dlog::table()."` (`bookid`, `memberid`, `bookname`, `type`, `size`, `createdate`) VALUES ('$bookId', '$uid', '{$book['bookname']}', '$type', '$size', NOW())");
    }
}