<?php
namespace Sigma\Flatlab\Console;

use App\Models\User;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;
use Sigma\Flatlab\Facades\Flatlab;
use Illuminate\Filesystem\Filesystem;
use Spatie\Permission\Models\Permission;
use Sigma\Flatlab\Console\Installable;
use Sigma\Flatlab\FlatlabMenu as Menu;

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

    protected $files;

    protected $signature = 'flatlab:install {nombre : El nombre del cliente}  {--f|force : Force overwrite of files}';

    protected $description = 'Instalacion de Flatlab';

    protected $force = false;

    public function __construct(FileSystem $files)
    {
        parent::__construct();
        $this->files = $files;
    }

    public function handle()
    {
        if(config('flatlab.instalada'))
        {
            $this->error('La plantilla ya esta instalada');
            exit;
        }
        $this->processOptions();
        $this->createEnvFile();
        $this->presetFlatlab();
        $this->createDatabase();
        $this->migrateDatabase();
        $this->seedDatabase();
        $this->publishConfiguracionesAssets();
        $this->yarnInstall();
    }

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

    private function presetFlatlab()
    {
        $this->comment('Realizando preset Flatlab');
        $this->call('ui',['type'=>'flatlab']);

    }

    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');
    }

    public function seedDatabase()
    {
        $this->seedRoles();
        $this->seedUsers();
        $this->seedMenu();
    }

    public function seedRoles()
    {
        app()['cache']->forget('spatie.permission.cache');

        Permission::create(['name'=>'mensajes-recibir']);
        Permission::create(['name'=>'admin-configuraciones']);
        Permission::create(['name'=>'admin-usuarios']);
        Permission::create(['name'=>'admin-menu']);
        Permission::create(['name'=>'gestion']);

        $role = Role::create([
            'name'=>'Administrador'
        ]);
        $role2 = Role::create([
            'name'=>'Gestor'
        ]);

        $role->givePermissionTo(['admin-usuarios','admin-menu','gestion','admin-configuraciones']);
        $role2->givePermissionTo(['gestion','mensajes-recibir']);
    }

    public function seedUsers()
    {
         User::truncate();

        $user1 = User::create([
        	'name'=>'Santiago Argilla',
        	'email'=>'sargilla@gmail.com',
        	'password'=>'$2y$10$zsy6ncNm0Qwwa45A1IH/gebY.bDcGWVCX0hs3aSmdQXEjKQIJzTfO',
            'settings' => '{}',
            'activated' => 1
        ]);

        $user2 = User::create([
            'name'=>'Mario Figge',
            'email'=>'mario@3tristestigres.com',
            'password'=>'$2y$10$algl8btSSqnaP1uDSFJIG.AExBWpsWVUB63LWU2iZyyLhWrhHRp/O',
            'settings' => '{}',
            'activated' => 1
        ]);

        $user3 = User::create([
            'name' => 'Hernan Cefarelli',
            'email' => 'hernancefarelli@gmail.com',
            'password' => '$2y$10$fGLPAOpBKT2Oy.ZDEW3CPOiGJ/gLbCxR/W46TUraOSEigZYTCi0Sq',
            'settings' => '{}',
            'activated' => 1
        ]);
        $user4 = User::create([
            'name' => 'David Zisele',
            'email' => 'davidzisele2016@gmail.com',
            'password' => '$2y$10$PsOwvS4XtqnVdio.PAaWLekAjX151kX9hUHLIgqf/CzxFsZKSBcUW',
            'settings' => '{}',
            'activated' => 1
        ]);

        $user1->assignRole('Administrador');
        $user2->assignRole('Administrador');
        $user3->assignRole('Administrador');
        $user4->assignRole('Administrador');
    }

    public function seedMenu()
    {
        Menu::truncate();

        Menu::create([
        	'nombre'=>'Dashboard',
        	'alias'=>'dashboard',
        	'menu'=>'admin',
        	'padre_id' => '0',
        	'tipo' => 'route',
        	'destino' => 'gestion.index',
        	'icono'=>'fas fa-tachometer-alt',
        	'orden' => '0',
            'permiso' => 'gestion'
        ]);

        Menu::create([
        	'nombre'=>'Menus',
        	'alias'=>'menus',
        	'menu'=>'admin',
        	'padre_id' => '0',
        	'tipo' => 'route',
        	'destino' => 'menus.index',
        	'icono'=>'fas fa-map-signs',
        	'orden' => '1',
            'permiso' =>'admin-menu'
        ]);

        $usuarios = Menu::create([
        	'nombre'=>'Usuarios',
        	'alias'=>'usuarios',
        	'menu'=>'admin',
        	'padre_id' => '0',
        	'tipo' => 'url',
        	'destino' => '#',
        	'icono'=>'fas fa-users',
        	'orden' => '2',
            'permiso' =>'admin-usuarios'
        ]);

        Menu::create([
        	'nombre'=>'Usuarios',
        	'alias'=>'usuarios-index',
        	'menu'=>'admin',
        	'padre_id' => $usuarios->id,
        	'tipo' => 'route',
        	'destino' => 'users.index',
        	'icono'=>'fas fa-users',
        	'orden' => '1',
            'permiso' =>'admin-usuarios'
        ]);

        Menu::create([
        	'nombre'=>'Roles',
        	'alias'=>'roles',
        	'menu'=>'admin',
        	'padre_id' => $usuarios->id,
        	'tipo' => 'route',
        	'destino' => 'roles.index',
        	'icono'=>'fas fa-id-card',
        	'orden' => '2',
            'permiso' =>'admin-usuarios'
        ]);

        Menu::create([
        	'nombre'=>'Permisos',
        	'alias'=>'permisos',
        	'menu'=>'admin',
        	'padre_id' => $usuarios->id,
        	'tipo' => 'route',
        	'destino' => 'permisos.index',
        	'icono'=>'fas fa-lock',
        	'orden' => '3',
            'permiso' =>'admin-usuarios'
		]);

		Menu::create([
        	'nombre'=>'Configuraciones',
        	'alias'=>'configuraciones',
        	'menu'=>'admin',
        	'padre_id' => '0',
        	'tipo' => 'route',
        	'destino' => 'configuraciones.index',
        	'icono'=>'fas fa-cogs',
        	'orden' => '20',
            'permiso' =>'admin-configuraciones'
        ]);
    }

    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');
    }

}
