<?php

namespace Ignite\Core\Database\Seeders;

use Ignite\Core\Entities\Group;
use Ignite\Core\Entities\Permission;

/**
 * php artisan db:seed --class="Ignite\Core\Database\Seeders\GroupPermissionTableSeeder"
 */
class GroupPermissionTableSeeder extends AbstractSeeder
{
    /**
     * The name of the data file.
     *
     * @var string
     */
    protected $file = 'core_group_permission.json';

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        parent::run();

        $strategy = $this->strategy('json', [
            'filepath' => $this->getFilepath($this->file)
        ]);

        /** @var \Illuminate\Support\Collection $sources */
        $sources = $strategy->run();
        $permissions = Permission::whereIn('key', $sources->pluck('permission_key'))
            ->get()
            ->keyBy('key');

        if ($permissions->isEmpty()) {
            echo 'No permissions were seeded.';
            return;
        }

        foreach ($sources as $source) {
            try {
                /** @var Group $group */
                $groups = Group::whereIn('key', explode('|', $source['group_name']))->get();
                $permission = $permissions[$source['permission_key']];
                foreach ($groups as $group) {
                    $hasPermission = $group->hasPermission($permission);
                    if (! $hasPermission) {
                        // dump("Giving {$permission->key} to {$group->name}");
                        $group->givePermissionTo($permission);
                    } elseif ($hasPermission) {
                        // dump("Already has permission {$permission->key} for {$group->name}");
                    }
                }
            } catch (\Exception $e) {
                echo $e->getMessage() . PHP_EOL;
                continue;
            }
        }

        // $this->debugShowGroupPermissionSummary();
    }

    /**
     */
    protected function debugShowGroupPermissionSummary()
    {
        $groups = Group::all();
        foreach ($groups as $group) {
            $permissions = $group->permissions()->get()->pluck('key')->toArray();
            sort($permissions);
            dump('GROUP: ' . $group->name);
            dump($permissions);
        }
    }
}
