<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\AIFeed;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use App\VendorCameras;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class AICamera extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ai:camera';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get Video or Image data from vehant Services';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->getData();
    }

    /**
     * Get vehant ai feed related data in xml formate
     */
    // private function getData($cameraId){
    //     $client = new GuzzleHttp\Client();
    //     \Log::info($client);
    //     if (!$cameraId){
    //         $res = $client->request('GET', 'https://phantom.vehant.in:60061/v1/api/foodkraft/alert/', [
    //             'X-Api-Key' => config('app.client_id')
    //         ]);
    //     }else{
    //         $res = $client->request('GET', 'https://phantom.vehant.in:60061/v1/api/foodkraft/alert/'.$cameraId, [
    //             'X-Api-Key' => config('app.client_id')
    //         ]);
    //     }
    //     if($res->getStatusCode()==200){
    //         $body=$res->getBody();
    //         \Log::info($body);
    //         $this->xmlParse($body);

    //     }
    // }
    private function getData(){
        $client = new \GuzzleHttp\Client(['verify' => false ]);
        \Log::info("This is the api key : ".config('app.client_id'));
        $res = $client->request('GET', 'https://phantom.vehant.in:60061/v1/api/foodkraft/alert/', [
            'headers' => ['X-Api-Key' => config('app.client_id')],
	        'Content-Type: application/json',
        ]);
        if($res->getStatusCode()==200){
            $body=$res->getBody();
            \Log::info(gettype($body));
            $this->xmlParse(json_decode($body));

        }
    }

    /**
     * parse xml and get required data
     */
    private function xmlParse($data){
        $folder = Carbon::now()->format('d-M-Y');
        //	$data = $data;
        //\Log::info($data);
        $count = count($data->body);
        \Log::info("Count of ai feeds : ".$count);
        $i=0;
        $alert = $data->body;
        \Log::info("Entering While Loop as count of data is : ".$count);
        while($i<$count){
            $data = $alert[$i];
            $data = json_decode(json_encode((array)simplexml_load_string($data)),true);
            $cameraId = $data['CameraInfo']['CameraId'];
            $input['cameraId'] = str_replace(' ', '', $cameraId);
            // For vendor Id and Client ID
            $cameraDetails = VendorCameras::where('cameraId', $input['cameraId'])
                                ->select('clientId','vendorId','cameraLocation')
                                ->get();
            \Log::info($cameraDetails);
            $cameraDetail = $cameraDetails[0];
            $clientId = $cameraDetail['clientId'];
            $vendorId = $cameraDetail['vendorId'];
            $cameraLocation = $cameraDetail['cameraLocation'];
            //To check weather folder exist or not
            
            // \Log::info("This is the Folder Path : ".$checkFolder);

            // $folderStatus = File::isDirectory($checkFolder);
            // if(! $folderStatus){
            // \Log::info("Folder Satatus : ".$folderStatus);
            // File::makeDirectory($checkFolder, 0755, true, true);
            // }
            $input['clientId'] = $clientId;
            $input['vendorId'] = $vendorId;
            $input['cameraLocation'] = $cameraLocation;
            $input['ai_Feed_Id'] = str_replace(' ', '', $data['AlertInfo']['Id']);
            $ai_feedType= $data['AlertInfo']['Type'];
            $input['ai_Feed_Type']= str_replace(' ', '', $ai_feedType);
            $input['ai_Feed_Time'] = str_replace(' ', '', $data['AlertInfo']['Time']);
            $input['ai_Feed_ROI'] = str_replace(' ', '',  $data['AlertInfo']['Attr']['roi']);
            $input['ai_Feed_Color'] = str_replace(' ', '', $data['AlertInfo']['Attr']['color']);
            $image_parts = explode(";base64,", $data['AlertInfo']['ImgData']);
            $image_type_aux = explode("image/", $image_parts[0]);
            $image_type = $image_type_aux[0];
            $image_base64 = base64_decode($image_parts[0]);
            
            $folder_path = $clientId.'-'.$vendorId.'/'. $input['cameraId'].'/'.$folder;
            $storage_path = storage_path('app/public/'.$folder_path);
            $filepath = $folder_path."/".$input['ai_Feed_Type'].$i.'.png';
            // $storage_path=$checkFolder;
            \Log::info("storagePath=".$storage_path);
            // \Log::info("new=".storage_path('app/public/'.$filepath));
            Storage::put('public/'.$filepath, $image_base64);
            
            // $filepath=public_path($filepath);
            $input['imageLink'] = "public/storage/".$filepath;
            // \Log::info("public path=".$public_path);
            // \Log::info(public_path("public/").$filepath);
            $input['videoId'] = str_replace(' ', '', $data['AlertInfo']['VidData']);

            $this->getVideo($clientId,$vendorId,$input['videoId'],$cameraId,$input,$folder_path);
            
            $i++;
        }
        // if($count>0){

        // }
    }


    /**
     * Get Video
     * 
     */
    private function getVideo($clientId,$vendorId,$videoId,$cameraId,$input,$folder_path){
        \Log::info("For video api\nClientID : ".$clientId."\nVendorId: ".$vendorId."\nVideoId : ".$videoId."\nCameraId : ".$cameraId."\nData is Below:");
        \Log::info($input);
        $client = new \GuzzleHttp\Client(['verify' => false ]);
        $res = $client->request('GET', "https://phantom.vehant.in:60061/v1/api/foodkraft/video/". $videoId, [
            'headers' => ['X-Api-Key' => config('app.client_id')],
	        'Content-Type: application/json',
        ]);

        if($res->getStatusCode()==200){
            $body=$res->getBody();
            if(json_decode($body)->statusCode == 200){      
                \Log::info($body);
                // $dirpath=$clientId.'/'.$vendorId.'/'. $cameraId.'/'.$folder.'/'. $videoId;
                $filepath=$folder_path.'/'. $input['videoId'];
                // $storage_path=storage_path().$filepath;
                Storage::put($filepath,$body);              
                $input['videoLink'] = "public/storage/".$filepath;
                \Log::info("\nData enterged in database\n");
            }
            else{
                $input['videoLink'] = 'no video found';
                \Log::info($body);
                \Log::info("\nData enterged in database\n");
            }
            
            AIFeed::create($input);
        }
        return ;
        
    }


    /**
     * Fire mail
     * 
     */
    private function sendMail(){
        \Log::info("mail Sent");
        $clientEmailId = 'anoop@uginfosystems.com';
        $vendorEmailId = 'anoop@uginfosystems.com';
        $adminEmailId = 'anoop@uginfosystems.com';
        $data['type'] = 'aiFeedsEmail';
        $data['subject'] = 'AI Feeds Alert Mail';
        $data['mailId'] = $clientEmailId;   
        $data['note'] = 'You have received this notification email informing that one or more anomalies have been detected at the kitchen associated with you. Kindly log in to your Foodskraft portal to view the same in detail and take necessary action.';
        $res = Mail::to($clientEmailId)
                ->cc($vendorEmailId)
                ->cc($adminEmailId)
                ->send(new SendMail($data));
    }
}
