<?php

namespace App\Console\Commands;

use App\Models\BmdaisData;
use App\Models\BmdaisMetadata;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class BmdDataStoreCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'bmd:store {type?} {--start_date=} {--end_date=} {--data_type=} {--station_no=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $type = $this->argument('type');

        if(!$this->argument('type')) {
            $type = $this->choice(
                'What is your bmd type?',
                ['get_bmdais_data', 'get_bmdais_metadata'],
                0
            );
        } else {
            $type = $this->argument('type');
        }

        if ($type === 'get_bmdais_data') {
            if(!$this->option('data_type')) {
                $data_type = $this->choice(
                    'What is your data type?',
                    ['temperature', 'rain_gauge', 'wind_speed', 'wind_direction', 'humidity', 'pressure'],
                    0
                );
            } else {
                $data_type = $this->option('data_type');
            }

            $returnData = $this->getBmdDataFromApi([
                "type" => $type,
                "data_start_date" => $this->option('start_date') ?? now()->format('Y-m-d'),
                "data_end_date" => $this->option('end_date') ?? now()->format('Y-m-d'),
                "data_type" => $data_type,
                "station_no" => "[{$this->option('station_no')}]"
            ]);

            if($returnData) {
                foreach ($returnData['data'] as $data) {
                    $bmdaisData = BmdaisData::where('data_date', $data['data_date'])
                        ->where('data_hour', $data['data_hour'])
                        ->where('data_type', $data['data_type'])
                        ->where('station_no', $data['station_no'])
                        ->firstOrNew();

                    $bmdaisData->data_hour = $data['data_hour'];
                    $bmdaisData->data_type = $data['data_type'];
                    $bmdaisData->value = $data[$data['data_type']];
                    $bmdaisData->data_date = $data['data_date'];
                    $bmdaisData->station_no = $data['station_no'];
                    $bmdaisData->last_updated_at = now();
                    $bmdaisData->save();
                }

                $this->info('Get BMD AIS Data Successfully Stored');
            }
        } elseif($type === 'get_bmdais_metadata') {
            $returnData = $this->getBmdDataFromApi([
                "type" => $type,
            ]);

            if($returnData) {
                dd($returnData);
                foreach ($returnData['data'] as $data) {
                    $bmdaisMetadata = BmdaisMetadata::where('station_no', $data['station_no'])->firstOrNew();
                    $bmdaisMetadata->station_name = $data['station_name'];
                    $bmdaisMetadata->division = $data['division'];
                    $bmdaisMetadata->district = $data['district'];
                    $bmdaisMetadata->station_type = $data['station_type'];
                    $bmdaisMetadata->station_no = $data['station_no'];
                    $bmdaisMetadata->latitude = $data['latitude'];
                    $bmdaisMetadata->longitude = $data['longitude'];
                    $bmdaisMetadata->last_updated_at = now();
                    $bmdaisMetadata->save();
                }

                $this->info('Get BMD AIS Metadata Successfully Stored');
            }
        } else {
            $this->error('Invalid Command Type. Please provide a valid command type.');
        }
    }

    public function getBmdDataFromApi(array $payload)
    {
        $config = [
            'username' => 'LEOTECH Dhaka',
            'password' => 'Leotech@1',
            "apiKey" => "2CsxcWcMc8Rfb64GopCp5QB1puey5LSTOZ9eClmApJKpo038jJnRsrAgSoPnS3QL",
        ];

        $payload = array_merge($config, $payload);

        $response = Http::post('http://ais.bmd.gov.bd:48080/bmdc12_apiservices/restservice_post.html', $payload);

        $returnData = $response->collect();

        if($response->ok()) {
            if(isset($returnData['tag']) && $returnData['tag'] === 'error') {
                $message = '';
                if(isset($returnData['data']['msg'])) {
                    $message .= $returnData['data']['msg'];
                }

                $this->error('Data fetch failed. Error Message : '.$message);

                return;
            }elseif(!isset($returnData['data'])){
                $message = '';
                if(isset($returnData['msg'])) {
                    $message .= $returnData['msg'];
                }

                $this->error('Data fetch failed. Error Message : '.$message);

                return;
            }
            return $returnData;
        } else {
            $this->error('Data fetch failed. Error Message : '.strip_tags($response->body()));
        }
    }
}
