<?php

namespace App\Console\Commands;

use App\Models\CSRNow\Country;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Console\Helper\Table;

class PushTo extends Command
{
    /**
     * This console command is for development purpose only, Do not use it in production unless you are sure what you are doing.
     * It will update the json file first then countries table in the database according to this (https://restcountries.com/v3.1 this api) API.
     *
     *
     *
     * @API_Link https://restcountries.com/v3.1
     */

    /**
     * @constant for active key
     */
    const IS_ACTIVE = 1;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push_to {arg1?} {arg2?} {--h}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command performs writing file in json and database update for some static data.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws FileNotFoundException
     */
    public function handle()
    {
        // this prints help section in console
        $this->printHelpSection();

        // arguments
        $arg1 = $this->argument('arg1');
        $arg2 = $this->argument('arg2');

        if (!$arg1 || !$arg2) {
            $this->newLine();
            $this->warn("Run: php artisan push_to --h for help.");
            die();
        }

        // if data is country and want to store in json
        if ($arg1 === 'country' && $arg2 === 'json') {
            $countries = Http::withoutVerifying()
                ->get('https://restcountries.com/v3.1/all?fields=name,cca2,timezones')
                ->json();
            $data = new Collection();
            foreach ($countries as $country) {
                $data->push([
                    'country_name' => $country['name']['common'],
                    'country_code' => $country['cca2'],
                    'timezones' => $country['timezones'][0],
                ]);
            }
        } // if data is country and want to store in db
        elseif ($arg1 === 'country' && $arg2 === 'db') {
            if ($this->confirm('Do you wish to continue ?')) {
                $countries = json_decode(Storage::disk('local')->get('json/countries-list.json'));
                DB::statement('SET FOREIGN_KEY_CHECKS=0');
                Country::truncate();
                DB::statement('SET FOREIGN_KEY_CHECKS=1');
                foreach ($countries as $country) {
                    Country::create([
                        'country_name' => $country->country_name,
                        'country_code' => $country->country_code,
                        'timezones' => json_encode($country->timezones),
                        'is_active' => self::IS_ACTIVE,
                    ]);
                }
            } else {
                die();
            }
        } else {
            $this->newLine();
            $this->error("Unsupported Arguments.");
            die();
        }

        $this->info(ucwords($arg1) . " data is up-to-date in {$arg2} !");

        return 0;
    }

    /**
     * Prints the help section
     */
    private function printHelpSection()
    {
        $help = $this->option('h');
        if ($help) {
            $this->newLine();
            $this->info('Example: php artisan push_to arg1 arg2');
            // Create a new Table instance.
            $table = new Table($this->output);

            // Set the table headers.
            $table->setHeaders([
                'Argument', 'Description', 'State'
            ]);

            // Set the contents of the table.
            $table->setRows([
                ['arg1', 'Determines what static data to push i.e. country.', 'Required'],
                ['arg2', 'Determines where to push i.e. json, db.', 'Required']
            ]);

            // Render the table to the output.
            $table->render();

            $this->newLine();
            $this->info('Example:');
            $this->info('Push static data to a json file.');
            $this->info('php artisan push_to country json');
            $this->info('Push static data to database.');
            $this->info('php artisan push_to country db');
            $this->newLine();
            die();
        }
    }
}
