<?php

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use App\Models\Pouzivatel\Pouzivatel;
use App\Models\Pracovisko\Pracovisko;
use App\Models\Pouzivatel\PouzivatelStavEnum;
use Spatie\Permission\Exceptions\RoleDoesNotExist;

/**
 * Class PouzivateliaDatabaseSeeder
 */
class PouzivateliaDatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $pek = factory(Pracovisko::class)->create([
            'kod' => '0000',
            'nazov' => 'S-EKA, spol. s r.o.'
        ]);

        $admin = [
            'login' => '0000-lukac',
            'meno' => 'Radoslav',
            'priezvisko' => 'Lukáč',
            'stav' => PouzivatelStavEnum::AKTIVNY(),
        ];

        factory(Pouzivatel::class)->make($admin)
            ->assignRole($this->getRole('admin'))
            ->pracovisko()
            ->associate($pek)
            ->save();
    }

    /**
     * @param $name
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
     */
    private function getRole($name)
    {
        try {
            $role = Role::findByName($name);
        } catch (RoleDoesNotExist $exception) {
            $role = Role::create(['name' => $name]);
        } finally {
            return $role;
        }
    }
}
