<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Chapters
 *
 * @author apple
 */
class Chapters extends BaseActiveRecord
{
    /**
     * 章节的具体内容，保存在txt文档里面
     * @var string
     */
    public $content;

    /**
     * 是否为图片，用来实现修改图片章节时自动删图片文件
     * @var boolean
     */
    public $oldIsImage;
    
    public static $aDisplay = array(1=>'显示', 0=>'隐藏');

    public static $aImage = array(0 => '否', 1 => '是');

    /**
     * @param string $className
     * @return Chapters
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'ig_chapter';
    }

    public function rules()
    {
        return array(
            array('chaptername,content,createdate', 'required'),
            array('chaptername', 'length', 'max'=>255),
            array('size', 'numerical', 'integerOnly' => true),
            array('chaptername,content,updatedate,display,isimage,size,sort', 'safe')
        );
    }

    public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'book' => array(self::BELONGS_TO, 'Books', 'bookid'),
		);
	}

    public function scopes()
	{
		return array(
			'published' => array(
				'condition'=>'display=1',
				'order' => 'chapterid ASC',
			),
		);
	}

    public function attributeLabels()
    {
        return array(
            'chapterid' => '章节ID',
            'chaptername' => '章节名',
            'content' => '内容',
            'createdate' => '创建时间',
            'updatedate' => '最后修改',
            'display' => '显示',
            'isvip' => 'VIP',
            'isimage' => '图片',
            'size' => '字数',
        );
    }
    
	/**
     * 可用行为列表
     * @return array
     */
    public function behaviors()
    {
        return array(
			// 自动填充创建时间
			'CreateAt' => array(
				'class' => 'application.models.behaviors.CreateAtBehavior',
			),
        );
    }
    
    public function beforeSave()
    {
        if ($this->isNewRecord)
        {
            $this->sort = 1;
            $criteria = new CDbCriteria();
            $criteria->condition = 'bookid = '.$this->bookid;
            $criteria->order = 'sort DESC';
            $criteria->limit = 1;
            $chapter = Chapters::model()->find($criteria);
            if (!empty($chapter))
            {
                $this->sort = $chapter->sort + 1;
            }
        }
        else
        {
            if ($this->oldIsImage && !$this->isimage)
            {
                // 删图片
                $oldChapter = Front::getChapterContent($this->bookid, $this->chapterid);
                if (preg_match('/\w+\.(gif|jpg)/is', $oldChapter))
                {
                    $path = Front::getBookFileSavePath($this->bookid);
                    $images = explode("\n", $oldChapter);
                    foreach ($images as $image)
                    {
                        $imageFile = $path . $image;
                        if (is_file($imageFile))
                        {
                            @unlink($imageFile);
                        }
                    }
                }
            }
        }

        return true;
    }
    
    public function afterSave()
    {
        if (!$this->isNewRecord)
        {
            $data = array('isimage' => $this->isimage, 'content' => $this->content);
            Front::updateChapter($this->chapterid, $this->bookid, $data);
        }
        else
        {
            Front::updateChapterCache($this->bookid);
        }

        return true;
    }
    
    public function beforeDelete()
    {
        Front::deleteChapter($this->chapterid, $this->bookid);
        
        return true;
    }
    
	/**
	 * 获取一个章节的内容
	 * @return string
	 */
	public function getContent()
	{
        return Front::getChapterContent($this->bookid, $this->chapterid);
	}
	
	/**
	 * 获取到章节的TXT文件
	 * @return string
	 */
	public function getTxtFile()
	{
	    return Front::getBookFileSavePath($this->bookid) . $this->chapterid . '.txt';
	}
	
	public function isDisplay()
	{
	    echo $this->display ? self::$aDisplay[$this->display] : '<font color=red>'.self::$aDisplay[$this->display].'</font>';
	}

    public function isVip()
    {
        echo $this->isvip ? '<font color=red>是</font>' : '否';
    }

    public function isImage()
    {
        echo $this->isimage ? '<font color=red>是</font>' : '否';
    }
}