<?php
/**
 * Description of iCrudCode
 *
 * @author yzxh24
 */
Yii::import('system.gii.generators.crud.CrudCode');

class iCrudCode extends CrudCode
{
    /**
     * 生成的代码存放module名
     */
    private $moduleName = null;

    /**
     * Action集成的父类
     */
    public $extendsActionClass = 'BaseAction';
    
    public function init()
    {
        if (Yii::app()->request->isPostRequest)
        {
        }
    }
    
    public function prepare()
	{
        $this->files = array();
		$templatePath = $this->templatePath;
		$controllerTemplateFile = $templatePath . DIRECTORY_SEPARATOR . 'controller.php';

		$this->files[] = new CCodeFile(
            $this->controllerFile,
            $this->render($controllerTemplateFile)
        );

		$files = scandir($templatePath);
		foreach ($files as $file)
		{
			if (is_file($templatePath . '/' . $file) && CFileHelper::getExtension($file) === 'php' && $file !== 'controller.php')
			{
				$this->files[] = new CCodeFile(
					$this->viewPath . DIRECTORY_SEPARATOR . $file,
					$this->render($templatePath . '/' . $file)
				);
			}
/**/
            if (is_dir($templatePath . '/' . $file) && 'crud' == $file)
            {
                $crudPath = $templatePath . '/' . $file;
                $crudFiles = scandir($crudPath);
                foreach ($crudFiles as $crudFile)
                {
                    if (is_file($crudPath . '/' . $crudFile) && CFileHelper::getExtension($crudFile) === 'php')
                    {
                        if (!empty($this->moduleName))
                        {
                            $path = $this->getPath();
                            $this->files[] = new CCodeFile(
                                $this->getPath() . DIRECTORY_SEPARATOR . $crudFile,
                                $this->render($crudPath . '/' . $crudFile)
                            );
                        }
                    }
                }
            }
/**/
		}
    }

    public function getPath()
    {
        return $this->getModule()->getControllerPath() . '/' . $this->getControllerID();
    }

    /**
     * 获取提交上来的控制器所带的模块名
     * @return string
     */
    public function getModuleName()
    {
        if(($pos = strpos($this->controller, '/')) !== false)
        {
			$this->moduleName = strtolower(substr($this->controller, 0, $pos));
        }

        return $this->moduleName;
    }

    /**
     * 获取控制器名
     * @return string
     */
    public function getControllerName()
    {
        return str_replace('Controller','', $this->getControllerClass());
    }

    /**
     * 输出一个头
     */
    public function description()
    {
        $date = date('Y-m-d H:i:s');
        echo <<<EOT
<?php
/**
 * Descriptions
 * @author yzxh24
 * @email yzxh24@gmail.com
 * @created $date
 */
EOT;
    }
}