<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class IndexAction extends AuthorAction
{
    public function run()
    {
        $chapter = $this->getController()->getChapter();
        $book = $this->isBookOwner($chapter['bookid']);
        
        $drafts = $this->db()->select()->from(Draft::table())->where(array('chapterid'=>$chapter['chapterid'],'deleted'=>0))->desc('sort')->find();

        if (empty($drafts) && $chapter['size'])
        {
            $chapterContent = Chapter::getContent($book['bookid'], $chapter['chapterid']);
            $explode = array_filter(explode("\n", $chapterContent));
            $tmp = array();
            foreach ($explode as $value)
            {
                $tmp[] = $value;
            }
            $count = count($tmp);
            $splice = 10;
            $num = $count > $splice ? ceil($count / $splice) : 1;
            for ($i = 0; $i < $num; $i++)
            {
                $remark = '第'.($i+1).'部分';
                $draftContent = $this->saveAnalyze(implode("\n", array_splice($tmp, 0, $splice)));
                $size = mb_strlen($draftContent, 'utf-8');
                $insertId = $this->db()->insert(Draft::table())->value(array('sort'=>$i,'authorid'=>$this->getAuthorId(),'author'=>$this->getAuthorName(),'uid'=>$this->uid(),'username'=>$this->userName(),'subject'=>$remark,'content'=>$draftContent,'size'=>$size,'createdate'=>CDATETIME,'chapterid'=>$chapter['chapterid'],'bookid'=>$book['bookid']))->q();
                $drafts[] = array(
                    'id' => $insertId,
                    'subject' => $remark,
                    'sort' => $i,
                    'chapterid' => $chapter['chapterid'],
                    'size' => $size,
                );
            }
            $drafts = array_reverse($drafts);
        }

        $cron = DraftCron::single()->isCron($chapter['chapterid']);

        $this->getController()->render('index', array(
                'book' => $book,
                'chapter' => $chapter,
        		'drafts'=>$drafts,
                'cron' => $cron,
            )
        );
    }
}