<?php

namespace Modules\Configuration\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Modules\Configuration\Repositories\OutletRepository;
use Modules\Configuration\Services\OutletService;
use Modules\Configuration\Repositories\DenominationRepository;
use Modules\Configuration\Services\DenominationService;
use Modules\Configuration\Repositories\MultipleCurrencyRepository;
use Modules\Configuration\Services\MultipleCurrencyService;
use Modules\Configuration\Repositories\PrinterRepository;
use Modules\Configuration\Services\PrinterService;
use Modules\Configuration\Repositories\CounterRepository;
use Modules\Configuration\Services\CounterService;
use Modules\Configuration\Repositories\CompanyRepository;
use Modules\Configuration\Services\SettingService;

class ConfigurationServiceProvider extends ServiceProvider
{
    use PathNamespace;

    protected string $name = 'Configuration';

    protected string $nameLower = 'configuration';

    /**
     * Boot the application events.
     */
    public function boot(): void
    {
        $this->registerCommands();
        $this->registerCommandSchedules();
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->loadMigrationsFrom(module_path($this->name, 'database/migrations'));
    }

    /**
     * Register the service provider.
     */
    public function register(): void
    {
        $this->app->register(EventServiceProvider::class);
        $this->app->register(RouteServiceProvider::class);
        
        // Register OutletRepository
        $this->app->singleton(OutletRepository::class, function ($app) {
            return new OutletRepository(new \Modules\Configuration\Models\Outlet());
        });
        
        // Register OutletService as singleton
        $this->app->singleton(OutletService::class, function ($app) {
            return new OutletService($app->make(OutletRepository::class));
        });

        // Register DenominationRepository
        $this->app->singleton(DenominationRepository::class, function ($app) {
            return new DenominationRepository(new \Modules\Configuration\Models\Denomination());
        });

        // Register DenominationService as singleton
        $this->app->singleton(DenominationService::class, function ($app) {
            return new DenominationService($app->make(DenominationRepository::class));
        });

        // Register MultipleCurrencyRepository
        $this->app->singleton(MultipleCurrencyRepository::class, function ($app) {
            return new MultipleCurrencyRepository(new \Modules\Configuration\Models\MultipleCurrency());
        });

        // Register MultipleCurrencyService as singleton
        $this->app->singleton(MultipleCurrencyService::class, function ($app) {
            return new MultipleCurrencyService($app->make(MultipleCurrencyRepository::class));
        });

        // Register PrinterRepository
        $this->app->singleton(PrinterRepository::class, function ($app) {
            return new PrinterRepository(new \Modules\Configuration\Models\Printer());
        });

        // Register PrinterService as singleton
        $this->app->singleton(PrinterService::class, function ($app) {
            return new PrinterService($app->make(PrinterRepository::class));
        });

        // Register CounterRepository
        $this->app->singleton(CounterRepository::class, function ($app) {
            return new CounterRepository(new \Modules\Configuration\Models\Counter());
        });

        // Register CounterService as singleton
        $this->app->singleton(CounterService::class, function ($app) {
            return new CounterService($app->make(CounterRepository::class));
        });

        // Register CompanyRepository
        $this->app->singleton(CompanyRepository::class, function ($app) {
            return new CompanyRepository(new \Modules\Configuration\Models\Company());
        });

        // Register SettingService as singleton
        $this->app->singleton(SettingService::class, function ($app) {
            return new SettingService($app->make(CompanyRepository::class));
        });
    }

    /**
     * Register commands in the format of Command::class
     */
    protected function registerCommands(): void
    {
        // $this->commands([]);
    }

    /**
     * Register command Schedules.
     */
    protected function registerCommandSchedules(): void
    {
        // $this->app->booted(function () {
        //     $schedule = $this->app->make(Schedule::class);
        //     $schedule->command('inspire')->hourly();
        // });
    }

    /**
     * Register translations.
     */
    public function registerTranslations(): void
    {
        $langPath = resource_path('lang/modules/'.$this->nameLower);

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, $this->nameLower);
            $this->loadJsonTranslationsFrom($langPath);
        } else {
            $this->loadTranslationsFrom(module_path($this->name, 'lang'), $this->nameLower);
            $this->loadJsonTranslationsFrom(module_path($this->name, 'lang'));
        }
    }

    /**
     * Register config.
     */
    protected function registerConfig(): void
    {
        $configPath = module_path($this->name, config('modules.paths.generator.config.path'));

        if (is_dir($configPath)) {
            $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));

            foreach ($iterator as $file) {
                if ($file->isFile() && $file->getExtension() === 'php') {
                    $config = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
                    $config_key = str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $config);
                    $segments = explode('.', $this->nameLower.'.'.$config_key);

                    // Remove duplicated adjacent segments
                    $normalized = [];
                    foreach ($segments as $segment) {
                        if (end($normalized) !== $segment) {
                            $normalized[] = $segment;
                        }
                    }

                    $key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);

                    $this->publishes([$file->getPathname() => config_path($config)], 'config');
                    $this->merge_config_from($file->getPathname(), $key);
                }
            }
        }
    }

    /**
     * Merge config from the given path recursively.
     */
    protected function merge_config_from(string $path, string $key): void
    {
        $existing = config($key, []);
        $module_config = require $path;

        config([$key => array_replace_recursive($existing, $module_config)]);
    }

    /**
     * Register views.
     */
    public function registerViews(): void
    {
        $viewPath = resource_path('views/modules/'.$this->nameLower);
        $sourcePath = module_path($this->name, 'resources/views');

        $this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);

        $this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);

        Blade::componentNamespace(config('modules.namespace').'\\' . $this->name . '\\View\\Components', $this->nameLower);
    }

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

    private function getPublishableViewPaths(): array
    {
        $paths = [];
        foreach (config('view.paths') as $path) {
            if (is_dir($path.'/modules/'.$this->nameLower)) {
                $paths[] = $path.'/modules/'.$this->nameLower;
            }
        }

        return $paths;
    }
}
