<?php
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://doc.swoft.org
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Commands\Common\Generate;

use Swoft\Console\Bean\Annotation\Command;
use Swoft\Console\Bean\Annotation\Mapping;
use Swoft\Console\Input\Input;
use Swoft\Console\Output\Output;


/**
 * generate controller layer commands
 *
 * @Command(name="gen-control",coroutine=false)
 */
class GenerateControlCommand
{
    private $templatesPath = "/Commands/Common/Generate/ClassTemplate";

    /**
     * this generate controller command
     *
     * @Usage
     * generate:controller [options]
     *
     * @Options
     * -c,--c the controller name  with namespace
     *
     * @Example
     * php swoft gen-control:controller -c "App\Controllers\V1\DemoController"
     *
     * @param Input  $input
     * @param Output $output
     *
     * @Mapping("controller")
     */
    public function generateController(Input $input, Output $output) 
    {
        $controllerName = $input->getOpt('c');
        if (empty($controllerName)) {
            $output->writeln("please input option -c", true, true);
        }

        $controllerParams = explode('\\', $controllerName);
        $controllerDir = alias("@app");
        $namespace = null;
        $fileName = array_pop($controllerParams);
    
        foreach( $controllerParams as $param ) {
            if ($param == "App") {
                $namespace = $param;
                continue;
            }

            $controllerDir .=  '/'.$param;
            $namespace .= '\\'.$param;

        }
        
        if ( ! is_dir($controllerDir) ) {
            mkdir($controllerDir, 0777);
        }

        $appPath = alias("@app");

        $controllerPath =  $controllerDir.'/'.$fileName.'.php';

        $templateContent = file_get_contents($appPath . $this->templatesPath . '/Controller/classTemplate');
        $templateContent = str_replace(
            [
                "{{NAMESPACE}}",
                "{{CLASS_NAME}}"

            ],
            [
                $namespace,
                ucfirst($fileName),
            ],
            $templateContent
        );

       file_put_contents($controllerPath, $templateContent);

    }

}