<?php

namespace App\Modules;

abstract class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function boot()
    {
        if ($module = $this->getModule(func_get_args())) {
            $viewsPath = $this->getModuleDirectory($module) . '/views';
            if (is_dir($viewsPath) && !empty(glob($viewsPath . '/*'))) {
                $this->loadViewsFrom($viewsPath, $module);
            }
        }
    }

    public function register()
    {
        if ($module = $this->getModule(func_get_args())) {
            $moduleDir = $this->getModuleDirectory($module);

            if ($moduleDir) {
                // Add routes
                $routes = $moduleDir . '/routes.php';
                if (file_exists($routes)) {
                    require $routes;
                }

                // Add events
                $events = $moduleDir . '/events.php';
                if (file_exists($events)) {
                    require $events;
                }
            }
        }
    }

    /**
     * Normalize module name and get correct directory path regardless of case
     */
    protected function getModuleDirectory($module)
    {
        $modulesBasePath = app_path() . '/Modules';
        foreach (glob($modulesBasePath . '/*', GLOB_ONLYDIR) as $dir) {
            if (strcasecmp(basename($dir), $module) === 0) {
                return $dir;
            }
        }
        return null;
    }

    public function getModule($args)
    {
        return (isset($args[0]) && is_string($args[0])) ? $args[0] : null;
    }
}
