<?php

namespace FluxCms\Core\Commands;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputArgument;

class MakeComponentCommand extends GeneratorCommand
{
    protected $name = 'flux-cms:make-component';

    protected $description = 'Create a new Flux CMS component';

    protected $type = 'Flux CMS Component';

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

    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Livewire\Web\Components';
    }

    protected function buildClass($name)
    {
        $stub = parent::buildClass($name);

        return str_replace('{{ componentName }}', $this->argument('name'), $stub);
    }

    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'The name of the component'],
        ];
    }

    public function handle()
    {
        parent::handle();
        $this->createView();
    }

    protected function createView()
    {
        $name = $this->argument('name');
        $viewPath = resource_path('views/livewire/web/components/'.strtolower($name).'.blade.php');

        if (! is_dir(dirname($viewPath))) {
            mkdir(dirname($viewPath), 0777, true);
        }

        if (file_exists($viewPath)) {
            $this->error('View already exists!');

            return;
        }

        $stub = $this->files->get(__DIR__.'/stubs/view.stub');
        $this->files->put($viewPath, $stub);
        $this->info('View created successfully.');
    }
}
