<?php

namespace Clevercherry\Backslash;

use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Container\Container;
use Clevercherry\Backslash\Events\BuildingMenu;
use Clevercherry\Backslash\Console\AdminLteMakeCommand;
use Clevercherry\Backslash\Console\MakeAdminLteCommand;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Clevercherry\Backslash\Http\ViewComposers\AdminLteComposer;

class BackslashServiceProvider extends BaseServiceProvider
{
    public function register()
    {
        $this->app->singleton(AdminLte::class, function (Container $app) {
            return new AdminLte(
                $app['config']['adminlte.filters'],
                $app['events'],
                $app
            );
        });
    }

    public function boot(
        Factory $view,
        Dispatcher $events,
        Repository $config
    ) {
        $this->loadViews();

        $this->publishConfig();

        $this->publishAssets();

        $this->registerViewComposers($view);

        static::registerMenu($events, $config);
    }

    private function loadViews()
    {
        $viewsPath = $this->packagePath('resources/views');

        $this->loadViewsFrom($viewsPath, 'backslash');

        $this->publishes([
            $viewsPath => base_path('resources/views/vendor/clevercherry/backslash'),
        ], 'views');
    }

    private function publishConfig()
    {
        $configPath = $this->packagePath('config/backslash.php');

        $this->publishes([
            $configPath => config_path('backslash.php'),
        ], 'config');

        $this->mergeConfigFrom($configPath, 'backslash');
    }

    private function publishAssets()
    {
        $this->publishes([
            $this->packagePath('resources/assets') => public_path('vendor/clevercherry/backslash'),
        ], 'assets');
    }

    private function packagePath($path)
    {
        return __DIR__."/../$path";
    }

    private function registerViewComposers(Factory $view)
    {
        $view->composer('backslash::page', AdminLteComposer::class);
    }

    public static function registerMenu(Dispatcher $events, Repository $config)
    {
        $events->listen(BuildingMenu::class, function (BuildingMenu $event) use ($config) {
            $menu = $config->get('backslash.menu');
            call_user_func_array([$event->menu, 'add'], $menu);
        });
    }
}
