<?php

namespace App\Providers;

use Carbon\Carbon;
use League\Fractal\Manager;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Seka\AisekV3UserAuth\Authentication;
use Dingo\Api\Transformer\Adapter\Fractal;
use App\Models\Pouzivatel\RolesPermissions;
use League\Fractal\Serializer\JsonApiSerializer;
use App\Models\Pouzivatel\PortalRolesPermissions;
use App\Models\Pouzivatel\RoleAndPermissionsAggregator;

/**
 * Class AppServiceProvider
 *
 * @package App\Providers
 */
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app['Dingo\Api\Transformer\Factory']->setAdapter(function ($app) {
            $fractal = new Manager();

            $fractal->setSerializer(new JsonApiSerializer(secure_url('/api')));

            return new Fractal($fractal);
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('production')) {
            URL::forceScheme('https');
        }

        Carbon::setLocale(config('app.locale'));

        $this->app->bind(Authentication::class, function ($app) {
            return new Authentication(getenv('AISEKV3_AUTH_URI'));
        });

        $this->aggregateRolesAndPermissions();
    }

    /**
     * Agregacia roli a opravneni pouzivatelov pre portal a vsetky jeho registrovane moduly
     *
     * @return void
     */
    protected function aggregateRolesAndPermissions(): void
    {
        $this->app->bind(PortalRolesPermissions::class, function () {
            return new PortalRolesPermissions();
        });

        $this->app->tag([
            PortalRolesPermissions::class,
        ], 'roleaopravnenia');

        $this->app->when(RoleAndPermissionsAggregator::class)
            ->needs(RolesPermissions::class)
            ->giveTagged('roleaopravnenia');
    }
}
