<?php
class Spider
{
    /**
     * 采集对象工厂
     * @param string $detialUrl
     * @param string $spiderName
     * @return Site_Base
     */
    public static function factory($detialUrl, $spiderName)
    {
        try
        {
            $className = self::getClass($spiderName);
            $spider = new $className($detialUrl);
        }
        catch (Exception $exce)
        {
            throw new SiteException('无法实例化采集类'.$className);
        }
        
        return $spider;
    }
    
    /**
     * 书籍搜索
     * @param string $spiderName
     * @param string $bookName
     * @param string $authorName
     * @return string|boolean
     */
    public static function search($spiderName, $bookName, $authorName)
    {
        $className = self::getClass($spiderName);
        if (method_exists($className, 'searchBook'))
        {
            return call_user_func_array(array($className , 'searchBook'), array($bookName , $authorName));
        }
        
        return false;
    }
    
	/**
     * 获取停止更新的采集目标站点列表
     * @return array
     */
    public static function getStopSiteList()
    {
        $path = COLLECT_PATH . 'stop';
        $stopList = array();
        if (is_dir($path))
        {
            $dirObj = new DirectoryIterator($path);
            foreach ($dirObj as $dir)
            {
                if ($dir->isFile())
                {
                    $stopList[] = $dir->getFilename();
                }
            }
        }
        
        return $stopList;
    }
    
    /**
     * 获取需要进行监控的站点列表
     * 有getNewList()方法的即是
     * @return array
     */
    public static function getMonitorList()
    {
        $path = COLLECT_PATH . 'Site';
        $denyList = array('Base');
        $stopList = self::getStopSiteList();
        $denyList = array_merge($denyList, $stopList);
        $monitorList = array();
        if (is_dir($path))
        {
            $dirObj = new DirectoryIterator($path);
            foreach ($dirObj as $dir)
            {
                if ($dir->isFile() && !in_array($dir->getBasename('.php'), $denyList))
                {
                    $class = $dir->getBasename('.php');
                    if (method_exists(self::getClass($class), 'getNewList'))
                    {
                        $monitorList[] = $class;
                    }
                }
            }
        }
        
        return $monitorList;
    }
    
    /**
     * 获取完整的类名
     * @param string $class
     * @return string
     */
    public static function getClass($class)
    {
        return 'Site_' . $class;
    }
}