<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Schema;
use File;

use App\Models\Modules;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // Run jobs natively - We could technically use an service worker program but it's better to keep things native for ease of deployment during early development. Once this is a big product it needs a service worker program.
        $schedule->command('queue:work --stop-when-empty --tries=3')->everyMinute()->withoutOverlapping()->runInBackground();
        
        // Read command manifests for the modules.
        try {
            if (Schema::hasTable('modules')) {
                foreach(Modules::all()->pluck('name') as $module) {

                    // Check if module commands file exists...
                    if(File::exists(base_path("app/Modules/$module/ModuleCommands.json"))) {
                        $manifest = json_decode(file_get_contents(base_path("app/Modules/$module/ModuleCommands.json")), true);
        
                        if($manifest !== null) {
                            foreach($manifest as $command) {
                                $schedule->command($command['command'])->cron($command['schedule']);
                            }
                        }
                    }
                }
            }
        }
        catch(Exception $ex) {}
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');

        try {
            if (Schema::hasTable('modules')) {
                foreach(Modules::all()->pluck('name') as $module) {
                    $this->load(base_path("app/Modules/$module/Commands"));
                }
            }
        }
        catch(Exception $ex) {}
    }
}
