<?php namespace Concore\Foundation\Providers;

use View;
use Illuminate\Support\ServiceProvider;
use Concore\Foundation\Providers\Traits\ExplicitViewLoaderTrait;
use Concore\Foundation\Commands\MigrateCommand;

class FoundationServiceProvider extends ServiceProvider {

	use ExplicitViewLoaderTrait;

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->routes();
		$this->config();
		$this->middleware();
	}

	/**
	 * Load utility functions, custom exceptions, view composers, form macros, custom validators.
	 * Register facades, service providers and aliases.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->composers();

		$this->loadViewsFrom(__DIR__.'/../../resources/views/', 'foundation');
		$this->loadTranslationsFrom(__DIR__.'/../../resources/lang', 'foundation');

		// Publishes

		$this->publishes([
			__DIR__.'/../../resources/views/' => base_path('resources/views/vendor/foundation'),
		], 'views');

		$this->publishes([
			__DIR__.'/../../migrations' => base_path('database/migrations'),
		], 'migrations');

		$this->app->bind('sculpt-model.medium','Concore\Foundation\Models\Media');
		$this->app->tag('sculpt-model.medium','sculpt-models');

		$loader = \Illuminate\Foundation\AliasLoader::getInstance();
		$this->app->bind('Concore\Foundation\Image\ImageManager','Intervention\Image\ImageManager');
		$loader->alias('imagefoundation', 'Concore\Foundation\Image\ImageManager');
		$loader->alias('Image', 'Concore\Foundation\Image\Facades\Image');

		$this->app->register('Krucas\Notification\NotificationServiceProvider');
		$loader->alias('Notification', 'Krucas\Notification\Facades\Notification');

		$this->app->register('Concore\Foundation\Providers\GcsFilesystemServiceProvider');

		$this->app->extend('command.migrate', function ($original, $app) {
			return new MigrateCommand($app['migrator']);
		});

	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

	private function composers()
	{
		View::composer('*', 'Concore\Foundation\Http\ViewComposers\GlobalComposer');
		View::composer('foundation::layouts.html', 'Concore\Foundation\Http\ViewComposers\LayoutsBodyComposer');
	}

	private function routes() {
		require __DIR__ . '/../Http/routes.php';
	}

	private function config() {
		// Merge config
		$this->mergeConfigFrom(
			__DIR__.'/../../config/foundation.php', 'foundation'
		);
	}

	public function middleware()
	{
		$this->app->make('router')->middleware('guest', 'Concore\Foundation\Http\Middleware\RedirectIfAuthenticated');
	}

}
