<?php
namespace App\API;

use App\Entity\PersonBiometrics;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\Session;  
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;  
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\Filesystem\Filesystem;


class Tech5DigitalApi{


    private $container;

    public function __construct(ContainerInterface $container) // <- Add this
    {
        $this->container = $container;
    }

    public function getReceiver()
    {
        return $this->container->getParameter('api_receiver'); // <- Access your param
    }

    public function getTech5BaseUrl()
    {
        return $this->container->getParameter('tech5BaseUrl'); // <- Access your param
    }

   /**
    * Call for T5 to create finger template Tested and Working GOOD
    */
   public function CreatefingerTemplate(PersonBiometrics $personBiometric, $sqr)
   {
        $fst = new Filesystem();
        try 
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = $client->post( $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", [
                'headers'=> [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                ],
                'body' => json_encode([
                    "tid"=> "Create_template_".$sqr,
                    "encounter_id"=>  $sqr."_FINGER_template",
                    "response"=>  true,
                    "faceThreshold"=> 6,
                    "fingerThreshold"=>  0.2,
                    "irisThreshold"=>  0.2,
                    "maxResults"=>  10,
                    "finger_data"=>  [
                        "live_scan_plain"=>$personBiometric->getAbisFingerJson()
                    ],
                    "request_type"=> "CreateTemplates"
                ])]);

            //$request = new Request('POST', $this->getTech5BaseUrl().'/T5CloudService/1.0/processRequest', $headers, $body);
            //$res = $client->sendAsync($request)->wait();
           // $body = $request->getBody();
            //echo $res->getBody();
            $body = $request->getBody()->getContents();

            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            //dump( $decodedResponse);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/createTemplate.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
             $state = "FAILED";
                //$fs->appendToFile('EventLogFiles.txt', "\r\n ".json_encode($error));
                $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GuzzleCreateTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
                $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GuzzleCreateTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
                $retour = Psr7\Message::toString($e->getResponse());
                /*echo "Error: " . $e->getMessage() . "\n";
                if ($e instanceof \GuzzleHttp\Exception\RequestException) {
                    echo "Request Body: " . $e->getRequest()->getBody()->getContents() . "\n";
                    if ($e->hasResponse()) {
                        echo "Response Body: " . $e->getResponse()->getBody()->getContents() . "\n";
                    }
                }*/
        }

        return $retour;
   }

   
   /**
    * Call for T5 to create finger template with JSON instead of biometrics [Tested and Working GOOD]
    */
   public function CreateTemplateWithJson($jsonObject, $sqr)
   {
        $fst = new Filesystem();
        try 
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = $client->post( $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", [
                'headers'=> [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                ],
                'body' => json_encode([
                    "tid"=> "Create_template_".$sqr,
                    "encounter_id"=>  $sqr."_FINGER_template",
                    "response"=>  true,
                    "faceThreshold"=> 6,
                    "fingerThreshold"=>  0.2,
                    "irisThreshold"=>  0.2,
                    "maxResults"=>  10,
                    "finger_data"=>  [
                        "live_scan_plain"=>$jsonObject
                    ],
                    
                    "request_type"=> "CreateTemplates"
                ])]);

            $body = $request->getBody()->getContents();

            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            //dump( $decodedResponse);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/createTemplateWithJson.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
             $state = "FAILED";
                //$fs->appendToFile('EventLogFiles.txt', "\r\n ".json_encode($error));
                $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GuzzleCreateTemplateWithJsonException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
                $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GuzzleCreateTemplateWithJsonException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
                $retour = Psr7\Message::toString($e->getResponse());
        }

        return $retour;
   }

    /**
    * Call for T5 to Enroll with finger Data Tested and Working GOOD
    */
   public function EnrollWithFingerData(PersonBiometrics $personBiometric, $sqr)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=> "Enroll_".$sqr,
                            "encounter_id"=>  $sqr."_FINGER_ENROLLMENT",
                            "response"=>  true,
                            "faceThreshold"=> 6.0,
                            "fingerThreshold"=>  0.2,
                            "irisThreshold"=>  0.2,
                            "maxResults"=>  10,
                            "finger_data"=>
                            [
                                "live_scan_plain"=>$personBiometric->getAbisFingerJson()
                            ],
                            "request_type"=> "Enroll"
                        ]
                    )
                ]
            );
            
            //$request = new Request('POST', $this->getTech5BaseUrl().'/T5CloudService/1.0/processRequest', $headers, $body);
            //$res = $client->sendAsync($request)->wait();
            // $body = $request->getBody();
            //echo $res->getBody();
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerData.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }

   /**
    * Call for T5 to Enroll with finger Tested and Working GOOD
    */
   public function EnrollWithFingerTemplate(PersonBiometrics $personBiometric, $sqr)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=> "Enroll_".$sqr,
                            "encounter_id"=>  $sqr."_FINGER_ENROLLMENT",
                            "response"=>  true,
                            "faceThreshold"=> 6.0,
                            "fingerThreshold"=>  0.2,
                            "irisThreshold"=>  0.2,
                            "maxResults"=>  10,
                            "finger_data"=>
                            [
                                "live_scan_plain"=>$personBiometric->getAbisTemplateJson()
                            ],
                            "request_type"=> "Enroll"
                        ]
                    )
                ]
            );
            
            //$request = new Request('POST', $this->getTech5BaseUrl().'/T5CloudService/1.0/processRequest', $headers, $body);
            //$res = $client->sendAsync($request)->wait();
            // $body = $request->getBody();
            //echo $res->getBody();
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerTemplate.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/EnrollWithFingerTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;    
   }
   
   /**
    * Call for T5 for Identification with finger data Tested and Working GOOD
    */
   public function IdentificationWithFingerData(PersonBiometrics $personBiometric, $sqr)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "Identification_".$sqr,
                            "response"=>  true,
                            "faceThreshold"=>  0.0,
                            "fingerThreshold"=>  0.0,
                            "irisThreshold"=>  0.0,
                            "maxResults"=>  10.0,
                            "finger_data"=>
                            [
                                "live_scan_plain"=>$personBiometric->getAbisTemplateJson()
                            ],
                            "request_type"=> "Identification"
                        ]
                    )
                ]
            );
            
            //$request = new Request('POST', $this->getTech5BaseUrl().'/T5CloudService/1.0/processRequest', $headers, $body);
            //$res = $client->sendAsync($request)->wait();
            // $body = $request->getBody();
            //echo $res->getBody();
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificationWithFingerData.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificationWithFingerDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificationWithFingerDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }
   
   /**
    * Call for T5 for Identification with finger Template Tested and Working GOOD
    */
   public function IdentificationWithFingerTemplate(PersonBiometrics $personBiometric, $sqr)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "Identification_".$sqr,
                            "response"=>  true,
                            "faceThreshold"=>  0.005,
                            "fingerThreshold"=>  0.005,
                            "irisThreshold"=>  0.005,
                            "maxResults"=>  10.0,
                            "finger_data"=>
                            [
                                "live_scan_plain"=>$personBiometric->getAbisTemplateJson()
                            ],
                            "request_type"=> "Identification"
                        ]
                    )
                ]
            );
            
            //$request = new Request('POST', $this->getTech5BaseUrl().'/T5CloudService/1.0/processRequest', $headers, $body);
            //$res = $client->sendAsync($request)->wait();
            // $body = $request->getBody();
            //echo $res->getBody();
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificatioWithFingerTemplate.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificatioWithFingerTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/IdentificatioWithFingerTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }
   
   /**
    * Call for T5 for get template by encountered id Tested and Working GOOD
    */
   public function getTemplatesByEncounteredId(PersonBiometrics $personBiometric, $sqr, $encounterId)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "gettemplates_".$sqr,
                            "encounter_id"=>  $encounterId,
                            "request_type"=>  "GetTemplates"
                        ]
                    )
                ]
            );
            
            $body = $request->getBody()->getContents();
            
            //Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GetTemplatesByEncounteredId.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GetTemplatesByEncounteredIdException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/GetTemplatesByEncounteredIdException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }

   /**
    * Call for T5 for delete by encountered id Tested and Working GOOD
    */
   public function deleteByEncounteredId(PersonBiometrics $personBiometric, $sqr)
   {
                $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "Delete_".$sqr,
                            "encounter_id"=>  $encounterId,
                            "response"=>  true,
                            "request_type"=>  "Delete"
                        ]
                    )
                ]
            );
            
            $body = $request->getBody()->getContents();
            
            //Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/DeleteRecord.txt', "\r\n ".date("d-m-Y H:i:s")." - Template creation : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/DeleteRecordException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/DeleteRecordException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }

   /**
    * Call for T5 for verification finger match by DataTested and Working GOOD
    */
   public function verificationFingerMatchByData(PersonBiometrics $personBiometric, $sqr, $sampleFp)
   {
        $fst = new Filesystem();
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "Verification_".$sqr,
                            "response"=>  true,
                            "faceThreshold"=>  0,
                            "fingerThreshold"=>  0,
                            "irisThreshold"=>  0,
                            "probeFingers" => [
                                "live_scan_plain" => $personBiometric->getAbisTemplateJson()
                            ],
                            "galleryFingers" => [
                                "live_scan_plain" => $sampleFp
                            ],
                            "request_type"=> "Verification"
                        ]
                    )
                ]
            );
             
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithData.txt', "\r\n ".date("d-m-Y H:i:s")." - Verification : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithDataException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }
   
   /**
    * Call for T5 for verification finger match by template Tested and Working GOOD
    */
   public function verificationFingerMatchByTemplate(PersonBiometrics $personBiometric, $sqr, $sampleFp)
   {
        $fst = new Filesystem();
        $pos = $sampleFp[0]['pos'];

        $probArray  = [];
        foreach ($personBiometric->getAbisTemplateJson() as $key) 
        {
            if($key['pos'] = $pos)
            {
                $probArray [] = 
                [
                    "pos"=> $key['pos'],
                    "data"=> null,
                    "template"=> $key['template'],
                    "quality"=>99
                ];
            }
        }
        //$personBiometric->getAbisTemplateJson()
       // dump($probArray);
        try
        {
            $client = new \GuzzleHttp\Client(['verify' => false]);
            $request = 
            $client->post(
                $this->getTech5BaseUrl()."/T5CloudService/1.0/processRequest", 
                [
                    'headers'=> 
                    [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
                    ],
                    'body' => 
                    json_encode(
                        [
                            "tid"=>  "Verification_".$sqr,
                            "response"=>  true,
                            "faceThreshold"=>  0.005,
                            "fingerThreshold"=>  0.005,
                            "irisThreshold"=>  0.005,
                            "probeFingers" => [
                                "live_scan_plain" => $probArray
                            ],
                            "galleryFingers" => [
                                "live_scan_plain" => $sampleFp
                            ],
                            "request_type"=> "Verification"
                        ]
                    )
                ]
            );
            
            $body = $request->getBody()->getContents();
            
            // Decode the JSON response if the API returns JSON
            $decodedResponse = json_decode($body, true);
            $retour = $decodedResponse;
            
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithTemplate.txt', "\r\n ".date("d-m-Y H:i:s")." - Verification : ".json_encode($decodedResponse));
            
        } catch (ClientException $e)
        {
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - request : ".Psr7\Message::toString($e->getRequest()));
            $fst->appendToFile('log/authProcess/'.date("Y")."/".date("d-m-Y").'/VerificationWithTemplateException.txt', "\r\n ".date("d-m-Y H:i:s")." - Response : ".Psr7\Message::toString($e->getResponse()));
            $retour = Psr7\Message::toString($e->getResponse());
        }
        return $retour;
   }

   public function verificationfingerTemplateCurl(PersonBiometrics $personBiometric, $sqr, $sampleFp)
   {
        
        $fst = new Filesystem();
        
        $pos = $sampleFp[0]['pos'];

        $probArray = [];
        foreach ($personBiometric->getAbisTemplateJson() as $key) 
        {
            if($key['pos'] = $pos )
            {
                $probArray []  = 
                [
                    "pos"=> $key['pos'],
                    "data"=> null,
                    "template"=> $key['template'],
                    "quality"=>99
                ];
            }
        }
        //$personBiometric->getAbisTemplateJson()
        //dump($probArray );

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://abis-9.tech5.tech/T5CloudService/1.0/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
            "tid": "Verification_'.$sqr.'",
            "response": true,
            "faceThreshold": 0.005,
            "fingerThreshold": 0.005,
            "irisThreshold": 0.005,
            "probeFingers": {
                "live_scan_plain": '.json_encode($probArray).'
            },
            "galleryFingers": {
                "live_scan_plain": '.json_encode($sampleFp).'
            },
            "request_type": "Verification"
        }',
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization: Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        //echo $response;
        
        // Decode the JSON response if the API returns JSON
        $decodedResponse = json_decode($response, true);
       /// $retour = $decodedResponse;

        return $decodedResponse;
   }

    public function verificationfingerTemplateCurlUpdated(PersonBiometrics $personBiometric, $sqr, $sampleFp)
   {
        
        $fst = new Filesystem();
        //$personBiometric->getAbisTemplateJson()
        //dump($probArray );

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://abis-9.tech5.tech/T5CloudService/1.0/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
            "tid": "Verification_'.$sqr.'",
            "response": true,
            "faceThreshold": 0.005,
            "fingerThreshold": 0.005,
            "irisThreshold": 0.005,
            "probeFingers": {
                "live_scan_plain": '.json_encode($personBiometric->getAbisTemplateJson()).'
            },
            "galleryFingers": {
                "live_scan_plain": '.json_encode($sampleFp).'
            },
            "request_type": "Verification"
        }',
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization: Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        //echo $response;
        
        // Decode the JSON response if the API returns JSON
        $decodedResponse = json_decode($response, true);
       /// $retour = $decodedResponse;

        return $decodedResponse;
   }

   public function ReadCryptographe($base64Cryptographe)
   {
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://idencode.tech5-sa.com/v1/cryptograph/decode',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{
                "cryptograph": "'.$base64Cryptographe.'"
            }',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: Basic Y2VkcmljLnRjaHVpc3NldUBreXZhbGFpZC5jb206QzNkcjFjQFQ1'
            ),
        ));
        
        $response = curl_exec($curl);
        
        $decodedResponse = json_decode($response, true);
        //curl_close($curl);
        //echo $response;
        return $decodedResponse;
   }

   public function saveDeviceInfo(Device $device, Request $request){

    //device infos            
        $deviceId = $request->get("deviceId");
        $batteryState = $request->get("batteryState");
        $isBatteryPlugIn = $request->get("isBatteryPlugIn");
        $packageName = $request->get("packageName");
        $appVersion = $request->get("appVersion");
        $appLongitude = $request->get("appLongitude");
        $appLatitude = $request->get("appLatitude");
        $deviceToken = $request->get("deviceToken");   
        
        if(!empty($deviceId) && !empty($batteryState) && !empty($isBatteryPlugIn) && !empty($packageName) && !empty($appVersion) && !empty($appLongitude) && !empty($appLatitude) && !empty($deviceToken)){
            // device infos persist   
            $device = new Device();
            $device->setDeviceInfo($deviceId);
            $device->setDeviceToken($deviceToken);
            $device->setGpsLatitude($appLatitude);
            $device->setGpsLongitude($appLongitude);
            $device->setBatteryState($batteryState);
            $device->setIsBatteryPlugIn($isBatteryPlugIn);
            $device->setPackage($packageName);
            $device->setAppVersion($appVersion);
            //$deviceRepository->add($device, false);

            $ret = [                
                    "Etat"=>"",
                    'Message' =>"Device saved succesfully !!!", 
                    "device"=>$device,
                ];
            
        }else
        {
            $return = [
                'Etat' =>'FAILED',
                'Message' =>"Paramètres requis manquants...", 
            ];
        }
        return $ret;
   }

    public function getAndSaveFingerPrintsFromRequestObjects(Request $request, SluggerInterface $slugger, $sqrRef)
    {        
        $fingerArrayT5 = array();
        $fingerArrayEm = array();
        $seacrhItems = array("\n", "\r");
        $replaceBy   = array("", "");
        
        //device infos
        $deviceId = $request->get("deviceId");
        $batteryState = $request->get("batteryState");
        $isBatteryPlugIn = $request->get("isBatteryPlugIn");
        $packageName = $request->get("packageName");
        $appVersion = $request->get("appVersion");
        $appLongitude = $request->get("appLongitude");
        $appLatitude = $request->get("appLatitude");
        $deviceToken = $request->get("deviceToken");

        //Person Biometrics Data persist
        $personBiometric = new PersonBiometrics();

        /** @var UploadedFile $pos1 */
        $pos1 = $request->files->get('fpr1');

        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos1) 
        {
            $originalFilename = pathinfo($pos1->getClientOriginalName(), PATHINFO_FILENAME);

            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos1->guessExtension();
            //dump($newFilename);die;
            // Move the file to the directory where they must be stored
            try {
                $pos1->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
            
            $personBiometric->setFp1($sqrRef.'/'.$newFilename);
            
            $p1 = 
            [
                "pos"=>1,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p1);
        }
        
        /** @var UploadedFile $pos2 */            
        $pos2 = $request->files->get('fpr2');

        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos2) 
        {
            $originalFilename = pathinfo($pos2->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos2->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos2->move(
                $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }                
            
            $personBiometric->setFp2($sqrRef.'/'.$newFilename);
            
            $p2 = 
            [
                "pos"=>2,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p2);
    
        }      
        
        /** @var UploadedFile $pos3 */            
        $pos3 = $request->files->get('fpr3');

        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos3) 
        {
            $originalFilename = pathinfo($pos3->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos3->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos3->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
        
            $personBiometric->setFp3($sqrRef.'/'.$newFilename);
            
            $p3 = 
            [
                "pos"=>3,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p3);
    
        }   
        
        /** @var UploadedFile $pos4 */            
        $pos4 = $request->files->get('fpr4');

        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos4) 
        {
            $originalFilename = pathinfo($pos4->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos4->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos4->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
        
            $personBiometric->setFp4($sqrRef.'/'.$newFilename);
            
            $p4 = 
            [
                "pos"=>4,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p4);
        }       

        /** @var UploadedFile $pos5 */            
        $pos5 = $request->files->get('fpr5');
        
        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos5) 
        {
            $originalFilename = pathinfo($pos5->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos5->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos5->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
        
            $personBiometric->setFp5($sqrRef.'/'.$newFilename);
            
            $p5 = 
            [
                "pos"=>5,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p5);
        }   

        /** @var UploadedFile $pos6 */            
        $pos6 = $request->files->get('fpl1');
        
        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos6) 
        {
            $originalFilename = pathinfo($pos6->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos6->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos6->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
                
            $personBiometric->setFp6($sqrRef.'/'.$newFilename);
            
            $p6 = 
            [
                "pos"=>6,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p6);
        }
        
        /** @var UploadedFile $pos7 */            
        $pos7 = $request->files->get('fpl2');
        
        // This condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos7) 
        {
            $originalFilename = pathinfo($pos7->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos7->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                $pos7->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
            
            $personBiometric->setFp7($sqrRef.'/'.$newFilename);
            
            $p7 = 
            [
                "pos"=>7,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p7);
        }
        
        /** @var UploadedFile $pos8 */            
        $pos8 = $request->files->get('fpl3');
        
        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos8) 
        {
            $originalFilename = pathinfo($pos8->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos8->guessExtension();

            // Move the file to the directory where they must be stored
            try {
                    $pos8->move(
                        $this->getParameter('kyvala_directory').'/'.$sqrRef,
                        $newFilename
                    );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }
            
            $personBiometric->setFp8($sqrRef.'/'.$newFilename);
            
            $p8 = 
            [
                "pos"=>8,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p8);
        }
        
        /** @var UploadedFile $pos9 */            
        $pos9 = $request->files->get('fpl4');
        
        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos9) 
        {
             $originalFilename = pathinfo($pos9->getClientOriginalName(), PATHINFO_FILENAME);
             // this is needed to safely include the file name as part of the URL
             $safeFilename = $slugger->slug($originalFilename);
             $newFilename = $safeFilename.'-'.uniqid().'.'.$pos9->guessExtension();
 
             // Move the file to the directory where they must be stored
            try {
                 $pos9->move(
                     $this->getParameter('kyvala_directory').'/'.$sqrRef,
                     $newFilename
                 );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }

            $personBiometric->setFp9($sqrRef.'/'.$newFilename);
           
            $p9 = 
            [
                "pos"=>9,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p9);
        }
        
        /** @var UploadedFile $pos10 */
        $pos10 = $request->files->get('fpl5');
        
        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($pos10) 
        {
            $originalFilename = pathinfo($pos10->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$pos10->guessExtension();
            
            // Move the file to the directory where they must be stored
            try {
                 $pos10->move(
                     $this->getParameter('kyvala_directory').'/'.$sqrRef,
                     $newFilename
                 );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }

            $personBiometric->setFp10($sqrRef.'/'.$newFilename);

            $p10 = 
            [
                "pos"=>10,
                "data"=>str_replace($seacrhItems, $replaceBy, base64_encode(\file_get_contents($this->getParameter('kyvala_directory').'/'.$sqrRef.'/'.$newFilename))),
            ];
            array_push($fingerArrayT5, $p10);
        }
        
        /** @var UploadedFile $selfie */            
        $face = $request->files->get('selfie');

        // this condition is needed because the 'brochure' field is not required
        // so the PDF file must be processed only when a file is uploaded
        if ($face)
        {
            $originalFilename = pathinfo($face->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $safeFilename = $slugger->slug($originalFilename);
            $newFilename = $safeFilename.'-'.uniqid().'.'.$face->guessExtension();
            
            // Move the file to the directory where they must be stored
            try {
                 $face->move(
                    $this->getParameter('kyvala_directory').'/'.$sqrRef,
                    $newFilename
                 );
            } catch (FileException $e) 
            {
                // ... handle exception if something happens during file upload
            }

            $personBiometric->setFace($sqrRef.'/'.$newFilename);
        }

        // device infos persist   
        $device = new Device();
        $device->setDeviceInfo($deviceId);
        $device->setDeviceToken($deviceToken);
        $device->setGpsLatitude($appLatitude);
        $device->setGpsLongitude($appLongitude);
        $device->setBatteryState($batteryState);
        $device->setIsBatteryPlugIn($isBatteryPlugIn);
        $device->setPackage($packageName);
        $device->setAppVersion($appVersion);
        //$deviceRepository->add($device, false);

        //$personBiometric->setFingerJson($fingerArrayT5);
        $personBiometric->setAbisFingerJson($fingerArrayT5);
        $personBiometric->setFireBaseToken($deviceToken);

        // on vérifie si au moins une empreinte as été envoyé sinon on rejete la requette
        if(!empty($pos1) || !empty($pos2) || !empty($pos3) || !empty($pos4) || !empty($pos5) || !empty($pos6) || !empty($pos7) || !empty($pos8) || !empty($pos9) || !empty($pos10)){
            $isPos = true;
        }else{
            $isPos = false;
        }


        $reslt = 
        [
            //"db"=>$fingerArrayEm,
            "t5Abis"=>$fingerArrayT5,
            "personBiometric"=>$personBiometric,
            "device"=>$device,
            "Etat"=>"SUCCESS",
            "isPosAvailable"=>$isPos // true false
        ];

        return $reslt;
    }
}