<?php

namespace App\Providers;

use App\Models\User;
use App\View\WidgetFactory;
use Illuminate\Support\ServiceProvider;

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

        \Route::bind('user', function ($value) {
            // Hack to have the URL case insensitive (also needed a vendor patch for login)
            $u = User::whereRaw('LOWER(name)=LOWER(?)', [$value])->first();
            // it may also be the _id directly
            if (!$u && is_numeric($value)) $u = User::find((int)$value);
            if (!$u) abort(404);
            return $u;
        });

        \Blade::directive('tooltip', function($arg) {
            $arge = e($arg);
            return 'aria-label="' . $arge . '" title="' . $arge . '"';
        });

        \Blade::directive('sr', function($arg) {
            $sr = str_replace('~', '&nbsp;', e($arg));
            return '<span class="sr-only">'.$sr.'</span>';
        });

        \Blade::directive('icon', function($arg) {
            // arg: classes... , alt text
            // tildes in alt text may be used to add nbsp to sr-only, they are removed from the tooltip.
            // giving no alt text makes it sr-hidden, with no tooltip
            $parts = explode(',', $arg, 2);
            if (count($parts) == 2) {
                list($classes, $title) = $parts;

                $classes = trim($classes);
                $title = trim($title);

                $notooltip = false;

                if (strpos($title, 'sr:') === 0) {
                    $notooltip = true;
                    $title = substr($title, 3);
                }

                $sr = str_replace('~', '&nbsp;', e($title));
                $tit = str_replace('~', '', e(trim($title, " \r\n\t:,")));

                return '<span class="sr-only">' . $sr . '</span>' .
                    '<i class="' . e($classes) . '" '.
                    ($notooltip ? '' : 'title="' . $tit . '"') .
                    ' aria-hidden=true></i>';
            } else {
                return '<i class="' . e(trim($arg)) . '" aria-hidden=true></i>';
            }
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(WidgetFactory::class, function () {
            return new WidgetFactory();
        });
    }
}