<?php

namespace Ignite\Core\Tests;

use Illuminate\Console\Application as Artisan;
use Ignite\Core\Entities\Group;
use Ignite\Core\Entities\User;
use Orchestra\Testbench\TestCase as BaseTestCase;

class TestCase extends BaseTestCase
{
    /**
     * Login as admin is more for readability.
     *
     * @param  int $id
     * @return User
     */
    protected function loginAsAdmin($id = 1)
    {
        /** @var User $user */
        try {
            $user = User::with(['groups'])->where('user_id', $id)->firstOrFail();
        } catch (\Exception $e) {
            $user = factory(User::class)->create();
            $group = factory(Group::class)->create();
            $user->groups()->save($group);
            $user->fresh()->load('groups');
        }

        if (! $user) {
            $this->assertInstanceOf(User::class, $user, 'Unable to find test user.');
        }

        $this->app['authorization']->forgetPermissions()->registerPermissions();

        $this->actingAs($user);

        return $user;
    }

    /**
     * Load the routes for a module or many modules.
     *
     * @param string|array $modules
     */
    protected function loadRoutes($modules)
    {
        if (is_string($modules)) {
            $modules = [$modules];
        }

        foreach ($modules as $key => $module) {
            $module = ucfirst(camel_case($module));
            $modules[$key] = realpath(__DIR__ . "/../../../modules/$module/Http/routes.php");
            require $modules[$key];
        }

        $routes = app(\Illuminate\Routing\Router::class)->getRoutes();
        app()->instance('routes', $routes);
        app()->rebinding('routes', function ($app, $routes) {
            $app['url']->setRoutes($routes);
        });
        app(\Illuminate\Routing\Router::class)->getRoutes()->refreshNameLookups();
    }

    /**
     * Load the helper functions.
     */
    protected function loadHelpers()
    {
        // Include helpers
        $helpers = [
            "amount.php",
            "date.php"
        ];

        foreach ($helpers as $helper) {
            require_once realpath(__DIR__ . "/../../../modules/Core/Helpers/$helper");
        }

        /*$helpers = [
            "scramble.php",
            "setting.php",
            "utility.php",
        ];

        foreach ($helpers as $helper) {
            require_once realpath(__DIR__ . "/../../../modules/Claim/Helpers/$helper");
        }*/
    }

    /**
     * Load and resolve commands.
     *
     * @param $commands
     */
    protected function loadCommands($commands)
    {
        $commands = is_array($commands) ? $commands : func_get_args();

        Artisan::starting(function ($artisan) use ($commands) {
            $artisan->resolveCommands($commands);
        });
    }

    /**
     * Get the aliases for the Ignite package.
     *
     * @param \Illuminate\Foundation\Application $app
     * @return array
     */
    protected function getPackageAliases($app)
    {
        return [
            'Validator' => \Illuminate\Support\Facades\Validator::class,
            'Form' => \Collective\Html\FormFacade::class,
            'Html' => \Collective\Html\HtmlFacade::class,
            'Flash' => \Laracasts\Flash\Flash::class,
        ];
    }

    /**
     * Reset the database.
     */
    protected function resetDatabase()
    {
        $this->artisan('migrate:reset', [
            '--database' => 'testing',
        ]);
    }

    /**
     * Seed the database for one or many modules.
     *
     * @param null|string|array $seeds
     */
    protected function seedModules($seeds)
    {
        if (! is_null($seeds) && is_string($seeds)) {
            $seeds = [$seeds];
        }

        $seeders = [
            'core' => '\Ignite\Core\Database\Seeders\CoreDatabaseSeeder',
        ];

        foreach ($seeders as $module => $seeder) {
            if (in_array($module, $seeds)) {
                $this->artisan('db:seed', [
                    '--class' => $seeder,
                    '--database' => 'testing',
                ]);
            }
        }
    }

    /**
     * Get the providers registered with the Ignite package.
     *
     * @param \Illuminate\Foundation\Application $app
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [
            \Nwidart\Modules\LaravelModulesServiceProvider::class,
            \Nwidart\Modules\Providers\BootstrapServiceProvider::class,
            \JeroenNoten\LaravelAdminLte\ServiceProvider::class,
            \Ignite\Core\Providers\ViewServiceProvider::class,
            \Ignite\Core\Providers\CoreServiceProvider::class,
            \Collective\Html\HtmlServiceProvider::class,
            \Laracasts\Flash\FlashServiceProvider::class,
            \Kris\LaravelFormBuilder\FormBuilderServiceProvider::class,
        ];
    }

    /**
     * Define environment setup.
     *
     * @param  \Illuminate\Foundation\Application  $app
     * @return void
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('app.env', 'testing');
        $app['config']->set('database.default', 'testing');
        $app['config']->set('database.connections.testing', [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'port' => '3306',
            'database' => getenv('MYSQL_DATABASE') ?: 'tests',
            'username' => getenv('MYSQL_USERNAME') ?: 'homestead',
            'password' => getenv('MYSQL_PASSWORD') ?: 'secret',
        ]);
        $app['config']->set('Core.admin', [
            'email' => getenv('ADMIN_EMAIL') ?: 'it@brightspot.email',
            'password' => getenv('ADMIN_PASSWORD') ?: 'br1ght3r1d34s!',
        ]);
    }
}
