<?php
define('ROOT_PATH', dirname(dirname(dirname(__FILE__))) . '/');
require_once ROOT_PATH . 'include/Db.class.php';
require_once ROOT_PATH . 'include/Cache.class.php';
require_once ROOT_PATH . 'include/Ubb.func.php';
require_once ROOT_PATH . 'model/model.php';
$_SYS = require_once ROOT_PATH . 'cache/Settings.inc.php';
extract($_SYS, EXTR_OVERWRITE);
$path = empty($_SYS['cfg_path']) ? '/' : '/' . $_SYS['cfg_path'];
$time = $_SERVER['REQUEST_TIME'];
$db = Db::getInstance();
$cache_config = array(
 	'core' => $_SYS['cfg_cachecore'],
 	'expire' => $_SYS['cfg_cachetime'],
 	'folder' => ROOT_PATH . 'cache/bookinfo',
 	'depth' => 2
);
$cache = Cache::getSingleton($cache_config);

define('CTIME', $time);
define('CDATE', date('Y-m-d'));
define('CDATETIME', date('Y-m-d H:i:s'));
define('DATA_DIR', ROOT_PATH . 'data/');
define('CACHE_DIR', ROOT_PATH . "cache/");
define('BOOK_CACHE', CACHE_DIR . 'book/');
define('BOOK_INFO', CACHE_DIR . 'bookinfo/');

/**
 * 所有数据均以json格式返回
 * @author yzxh24
 */
class iServer
{
    /**
     * 取得小说的章节列表
     * @param int $bookId
     * @param int $num 获取的章节数，默认全部获取
     * @return array
     */
    public static function getChapterList($bookId, $num = 0)
    {
        $book = getBookInfo($bookId);
        $result = array(
            'list' => getChapterList($bookId),
            'last' => (empty($book) ? array() : array('lastChapterId'=>$book['lastchapterid'],'lastChapterName'=>$book['lastchaptername'],'lastUpdate'=>$book['updatedate'])),
        );

        return $result;
    }

    /**
     * 获取最新章节
     * @param int $bookId
     * @return array
     */
    public static function getLastChapter($bookId)
    {
        $book = getBookInfo($bookId);
        if (empty($book))
        {
            return array();
        }
        return array('lastChapterId'=>$book['lastchapterid'],'lastChapterName'=>$book['lastchaptername'],'lastUpdate'=>$book['updatedate']);
    }

    /**
     * 获取一个小说的信息
     * @param int $bookId
     * @return array
     */
    public static function getBook($bookId)
    {
        return fetchBookInfo($bookId);
    }

    /**
     * 获取小说封面
     * @param int $bookId
     * @return string
     */
    public static function getBookCover($bookId)
    {
        $cover = '';
        $book = getBookInfo($bookId);
        $image = empty($book['image']) ? '' : $GLOBALS['path'] . setting('txtpath') . '/' . $book['typeid'] . '/' . getFolder($bookId) . '/' . $bookId . '/' . $book['image'];
        if ($image)
        {
            $cover = $image;
        }
        return array('file' => $cover);
    }

    /**
     * 获取一个章节的内容，同时返回当前章节的上一章、下一章信息
     * @param int $bookId
     * @param int $chapterId
     * @return array
     */
    public static function getChapterContent($bookId, $chapterId, $isAPI = false)
    {
        $list = array(
            17270,
            14964,
            13949,
            14447,
            17322,
            7833,
            17336,
            15457,
            15270,
            15920,
            6129,
            14365,
            13140,
            17119,
            16502,
            15823,
            473,
            11497,
            14055,
            6128,
            15953,
            9269,
            15849,
            14053,
            15242,
            14583,
            17133,
            17397,
            1771,
            15991,
            17249,
            13948,
            16216,
            8287,
            15524,
            14049,
            14372,
            8914,
            14840,
            9528,
            16470,
            16049,
        );
        $array = array();
        $chapterCache = getChapters($bookId, $chapterId);
        $array['bookid'] = $bookId;
        $array['chapterid'] = $chapterId;
        $array['name'] = $chapterCache['current']['chaptername'];
        //$array['content'] = preg_replace(array('/\n/', '/\s/is'), array("<br/>", '&nbsp;'), Chapter::single()->getContent($bookId, $chapterId));
        $book = getBookInfo($bookId);
        if (!$isAPI && in_array($bookId, $list) && $chapterId == $book['lastchapterid'] && ((time() - strtotime($book['updatedate'])) < 1800))
        {
            $array['content'] = '手打中，清稍后...';
        }
        else
        {
            $array['content'] = Chapter::single()->getContent($bookId, $chapterId);
        }

        if ($chapterCache['next'])
        {
            $array['next'] = array('chapterid'=>$chapterCache['next']['chapterid'],'chaptername'=>$chapterCache['next']['chaptername']);
        }

        if ($chapterCache['prev'])
        {
            $array['prev'] = array('chapterid'=>$chapterCache['prev']['chapterid'],'chaptername'=>$chapterCache['prev']['chaptername']);
        }

        return $array;
    }

    /**
     * 获取最新列表
     * @param int $num
     * @param int $offset
     * @return array
     */
    public static function getNewList($num = 20, $offset = NULL)
    {
        $limit = ' LIMIT '.(is_null($offset) ? '' : $offset.',').$num;
        $sql = 'SELECT b.bookid,b.bookname,b.author,b.updatedate,b.lastchapterid,b.lastchaptername,t.typename FROM '.Book::table().' AS b INNER JOIN `'.Types::table().'` AS t ON t.typeid = b.typeid WHERE b.view = 1 ORDER BY b.updatedate DESC '.$limit;
        $updateList = $GLOBALS['db']->setQueryString($sql)->find();

        return $updateList;
    }

    /**
     * 搜索（只给出30条结果)
     * @param string $key
     * @param string $type
     * @return array
     */
    public static function search($key, $type = 1)
    {
        $condition = $type == 1 ? "bookname like '%{$key}%'" : "author LIKE '%{$key}%'";
        $sql = "SELECT bookid,size,b.typeid,bookname,bookinfo,lastchaptername,lastchapterid,updatedate,author,status,datatype,t.typename
        		FROM `".Book::table()."` AS b
        		INNER JOIN `".Types::table()."` AS t ON t.typeid = b.typeid
        		WHERE {$condition} ORDER BY click DESC LIMIT 30";
        $result = $GLOBALS['db']->setQueryString($sql)->find();
        if (empty($result))
        {
            $result = array();
        }
        return $result;
    }

    public static function apiSearch($bookName, $authorName)
    {
        $sql = "SELECT bookid,size,b.typeid,bookname,bookinfo,lastchaptername,lastchapterid,updatedate,author,status,datatype,t.typename
        		FROM `".Book::table()."` AS b
        		INNER JOIN `".Types::table()."` AS t ON t.typeid = b.typeid
        		WHERE bookname='{$bookName}' AND author='{$authorName}' limit 1";
        $result = $GLOBALS['db']->setQueryString($sql)->find(true);

        return array('bookid' => $result['bookid']);
    }

    /**
     * 首页5条推荐地址
     * @static
     * @return array
     */
    public static function indexHot()
    {
        return array(
            array('bookid' => 13121, 'bookname' => '天才医生', 'author' => '柳下挥'),
            array('bookid' => 14354, 'bookname' => '永生', 'author' => '梦入神机'),
            array('bookid' => 14194, 'bookname' => '修真世界', 'author' => '方想'),
            array('bookid' => 17124, 'bookname' => '通天之路', 'author' => '无罪'),
            array('bookid' => 17370, 'bookname' => '焚天', 'author' => '流浪的蛤蟆'),
        );
    }

    /**
     * 获得分类列表
     * @static
     * @return array
     */
    public static function typeList()
    {
        return array(
            array(1 => '武侠', 14 => '纯爱', 15 => '情感', 16 => '修真'),
            array(25 => '异陆', 26 => '仙侠', 27 => '竞技', 28 => '魔法'),
            array(40 => '剧本', 41 => '美文', 13 => '校园', 12 => '网游'),
            array(11 => '历史', 2 => '玄幻', 3 => '言情', 4 => '女生'),
            array(5 => '异能', 6 => '都市', 7 => '科幻', 8 => '鬼灵'),
            array(9 => '名著', 10 => '战争', 39 => '同人', 42 => '其他'),
        );
    }

    /**
     * 首页热门小说推荐
     * @static
     * @return array
     */
    public static function indexCommend()
    {
        return array(
            //array(
                array('bookid' => 5659, 'bookname' => '斗破苍穹'),
                array('bookid' => 8147, 'bookname' => '武神'),
                array('bookid' => 473, 'bookname' => '凡人修仙传'),
            //),
            //array(
                array('bookid' => 15270, 'bookname' => '遮天'),
                array('bookid' => 6128, 'bookname' => '仙逆'),
                array('bookid' => 7708, 'bookname' => '猎国'),
                array('bookid' => 15920, 'bookname' => '天珠变'),
                array('bookid' => 14354, 'bookname' => '永生'),
            //),
            //array(
                array('bookid' => 14964, 'bookname' => '重生之贼行天下'),
                array('bookid' => 11497, 'bookname' => '异世邪君'),
                array('bookid' => 14372, 'bookname' => '吞噬星空'),
            //),
            //array(
                array('bookid' => 14298, 'bookname' => '超级医生'),
                array('bookid' => 14055, 'bookname' => '召唤万岁'),
                array('bookid' => 7486, 'bookname' => '步步生莲'),
            //),
        );
    }

    /**
     * 首页全本推荐
     * @static
     * @return array
     */
    public static function indexOver()
    {
        return array(
            //array(
                array('bookid' => 3, 'bookname' => '星辰变'),
                array('bookid' => 6533, 'bookname' => '阳神'),
                array('bookid' => 505, 'bookname' => '长生界'),
                array('bookid' => 6507, 'bookname' => '九鼎记'),
            //),
            //array(
                array('bookid' => 6266, 'bookname' => '盘龙'),
                array('bookid' => 576, 'bookname' => '斗罗大陆'),
                array('bookid' => 926, 'bookname' => '近身保镖'),
            //),
        );
    }

    /**
     * 一次返回首页所有相关内容，防止多次请求造成资源浪费
     * @static
     * @return array
     */
    public static function index()
    {
        return array(
            'getNewList' => self::getNewList(10),
            'indexHot' => self::indexHot(),
            'indexCommend' => self::indexCommend(),
            'indexOver' => self::indexOver(),
            'typeList' => self::typeList(),
        );
    }

    /**
     * 检查是否有新的章节操作记录
     * @static
     * @param  int $lastId
     * @return int
     */
    public static function getModify($lastId)
    {
        $sql = 'SELECT id,bid,cid,type FROM '.ChapterLog::table().' WHERE id > '.$lastId;
        $result = $GLOBALS['db']->setQueryString($sql)->find();
        if (0 >= count($result))
        {
            // 已经是最新
            return 0;
        }
        $return = array();
        foreach ($result as $item)
        {
            $return[] = array($item['id'], $item['bid'], $item['cid'], $item['type']);
        }

        return $return;
    }
}

$method = $_GET['a'];
if (!method_exists(iServer, $method))
{
    die('Hacking Attempt');
}

unset($_GET['a']);
//print_r($_GET);die;
$result = call_user_func_array(array('iServer', $method), $_GET);
echo json_encode($result);