<?php
namespace Sargilla\Flatlab4\Console;

use Illuminate\Console\Command;
use Sargilla\Flatlab4\Facades\Flatlab4;
use Illuminate\Filesystem\Filesystem;
use Sargilla\Flatlab4\Console\Installable;

/**
 * Class Publish FlatLab.
 */
class InstallFlatlab4 extends Command
{
    use Installable;

    protected $files;

    /**
     * The name and signature of the console command.
     */
    protected $signature = 'flatlab4:install {nombre : El nombre del cliente}  {--f|force : Force overwrite of files}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Instalacion de Flatlab4';

    /**
     * Force overwrite of files.
     *
     * @var bool
     */
    protected $force = false;

    /**
     * Create a new command instance.
     *
     * @param \Illuminate\Filesystem\Filesystem $files
     *
     */
    public function __construct(FileSystem $files)
    {
        parent::__construct();
        $this->files = $files;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if(config('flatlab4.instalada'))
        {
            $this->error('La plantilla ya esta instalada');
            exit;
        }
        $this->processOptions();
        $this->createEnvFile();
        $this->presetFlatlab4();
        $this->createDatabase();
        $this->migrateDatabase();
      //  $this->publishConfig();
        $this->publishConfiguracionesAssets();
        $this->yarnInstall();
    }

    private function createEnvFile()
    {
        $file = Flatlab4::compile($this->files->get(FLATLAB4_PATH.'\stubs\.env'),['DATABASE' => $this->argument('nombre')]);
        $this->files->put(base_path('.env'), $file);
    }

    private function presetFlatlab4()
    {
        $this->comment('Realizando preset Flatlab4');
        $this->call('ui',['type'=>'flatlab4']);

    }

    private function createDatabase()
    {
       $this->comment('Creando base de datos');
       $this->call('db:create');
    }

    private function migrateDatabase()
    {
        config([
            'database.connections.mysql.username' =>'root',
            'database.connections.mysql.password' => 'root',
             ]);
        $this->comment('Migrando base de datos');
        $this->call('migrate:fresh' ,[
            '--seed' => true,
        ]);
    }

    private function publishConfig()
    {
        $this->install(Flatlab4::config());
    }

    private function publishConfiguracionesAssets()
    {
        $this->comment('Publicando Assets de Configuraciones');
        $this->call('vendor:publish',['--tag'=>'configuraciones']);
    }

    private function yarnInstall() {
        $this->comment('Instalando paquetes');
        passthru('yarn install');
        $this->comment('Compilando Paquetes');
        passthru('yarn run dev');
    }

    private function processOptions()
    {
        $this->force = $this->option('force');
    }

}
