<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;

class HardikController extends GeneratorCommand {

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'hardik:controller {name}';
    protected $controller_folder = 'AdminAuth';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create New Controller with data.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
//    public function __construct() {
//        parent::__construct();
//    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        $name = $this->argument('name');

        $controller_name = ucfirst($name) . 'Controller';
        $controller = '../app/Http/Controllers/'.$this->controller_folder.'/'. $controller_name;

        $controller_path = $this->getPath($controller);

        $this->files->put($controller_path, $this->buildClass2($name, 'controller'));
        $this->info($controller_name .'  created successfully.');
    }

    protected function getStub()
    {
        return __DIR__ . '/stubs/controller.stub';
    }

    protected function getPath($name) {
        $name = str_replace_first($this->rootNamespace(), '', $name);
        return $this->laravel['path'] . '/' . str_replace('\\', '/', $name) . '.php';
    }
    
    protected function buildClass2($name,$stub_file)
    {
        $stub = $this->files->get($this->getStub());
        return $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
    }

     protected function replaceNamespace(&$stub, $name)
    {
       $stub = str_replace(
            ['DummyNamespace', 'DummyRootNamespace'],
            ['App\Http\Controllers\\'.$this->controller_folder, $this->rootNamespace()],
            $stub
        );
        return $this;
    }
    
     protected function getNamespace($name)
    {
        return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
    }

    protected function replaceClass($stub, $name)
    {
        $class = str_replace($this->getNamespace($name).'\\', '', $name);
        $stub = str_replace('DummyRoute', $class, $stub);
        $stub = str_replace('DummyTitle', ucwords($name), $stub);
        $stub = str_replace('DummyMenu', strtolower($name),$stub);
        $stub = str_replace('DummyClass', ucfirst($name).'Controller',$stub);
        
        return str_replace('DummyRoute', $class, $stub);
    }
    protected function rootNamespace()
    {
        return $this->laravel->getNamespace();
    }
    
    
}
