<?php

/**
 * Generator
 *
 * @category   Sakle
 * @package    org.sabel.sakle
 * @author     Ebine Yutaka <ebine.yutaka@sabel.jp>
 * @copyright  2004-2008 Mori Reo <mori.reo@sabel.jp>
 * @license    http://www.opensource.org/licenses/bsd-license.php BSD License
 */
class Generator extends Sabel_Sakle_Task
{
  public function run()
  {
    $environment = $this->getEnvironment();
    $target = $this->checkArguments();
    
    if ($target === "model") {
      $this->generateModel($environment);
    } elseif ($target === "controller") {
      // @todo
    }
  }
  
  private function generateModel($environment)
  {
    define("ENVIRONMENT", $environment);
    Sabel_DB_Config::initialize(new Config_Database());
    
    $models = array();
    array_shift($this->arguments);
    
    foreach ($this->arguments as $mdlName) {
      $filePath = MODELS_DIR_PATH . DS . $mdlName . ".php";
      if (file_exists($filePath)) {
        $classFile = $mdlName . ".php";
        $this->warning("model '{$classFile}' already exists. (SKIP)");
      } else {
        $columns = MODEL($mdlName)->getColumnNames();
        $lines   = array();
        $lines[] = "<?php" . PHP_EOL;
        $lines[] = "Sabel_DB_Model_Localize::setColumnNames(";
        $lines[] = "  \"{$mdlName}\",";
        $lines[] = "  array(";
        
        foreach ($columns as $column) {
          $lines[] = "    \"{$column}\" => \"{$column}\",";
        }
        
        $lines[] = "  )";
        $lines[] = ");" . PHP_EOL;
        $lines[] = "class {$mdlName} extends Sabel_DB_Model";
        $lines[] = "{";
        $lines[] = "  ";
        $lines[] = "}";
        
        $this->success("create model {$mdlName}");
        $fp = fopen($filePath, "w");
        fwrite($fp, implode(PHP_EOL, $lines));
        fclose($fp);
      }
    }
  }
  
  private function generateController()
  {
    
  }
  
  private function getEnvironment()
  {
    if (Sabel_Console::hasOption("e", $this->arguments)) {
      $opts = Sabel_Console::getOption("e", $this->arguments);
      if (($env = environment($opts[0])) === null) {
        $this->error("invalid environment.");
        exit;
      } else {
        return $env;
      }
    } else {
      return DEVELOPMENT;
    }
  }
  
  private function checkArguments()
  {
    $arguments = $this->arguments;
    
    if (count($arguments) < 2) {
      $this->usage();
      exit;
    }
    
    $target = $arguments[0];
    
    if (!in_array($target, array("model", "controller"), true)) {
      $this->usage();
      exit;
    }
    
    return $target;
  }
  
  public function usage()
  {
    echo "Usage: sakle Generator\n";
  }
}
