<?php

namespace App\Controller;

use App\Services\ChargeAngelsApi;
use App\Services\EmailService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class BorneController extends AbstractController

{
    public $Charge;
    private ChargeAngelsApi $client;

    public function __construct(ChargeAngelsApi $client)
    {
        $this->client = $client;
    }
    #[Route('/borne/{id}', name: 'app_borne')]
    public function index($id): Response
    {
        try {
            $borneResponse = $this->client->request(Request::METHOD_GET, sprintf('api/charging-stations/%s', $id));
            $borne = json_decode($borneResponse->getContent(), true);
        } catch (\Exception $exception) {
            dd($exception);//TODO Error
        }
        return $this->render('borne/index.html.twig', [
            'controller_name' => 'BorneController',
            'borne' => $borne
        ]);
    }
    #[Route('/borne/{id}/{email}', name: 'app_borne_mail')]
    public function index_with_mail($id,$email): Response
    {
        try {
            $borneResponse = $this->client->request(Request::METHOD_GET, sprintf('api/charging-stations/%s', $id));
            $borne = json_decode($borneResponse->getContent(), true);
        } catch (\Exception $exception) {
            dd($exception);//TODO Error
        }
        return $this->render('borne/index.html.twig', [
            'controller_name' => 'BorneController',
            'borne' => $borne,
            'email'=>$email
        ]);
    }
    // Calcul nombre de charge ###################################################################################################
    #[Route('/charge/{id}', name: 'app_charge')]
    public function charge($id): Response
    {
        try {
            $borneResponse = $this->client->request(Request::METHOD_GET, sprintf('api/charging-stations/%s', $id));
            $borne = json_decode($borneResponse->getContent(), true);
        } catch (\Exception $exception) {
            dd($exception);//TODO Error
        }
        return $this->render('borne/estimation.html.twig', [
            'controller_name' => 'BorneController',
            'borne' => $borne
        ]);
    }

    // JSON Call #################################################################################################################
    #[Route('/json/borne/liste', name: 'json_borne_liste', methods: ['GET'])]
    public function getList(Request $request): JsonResponse
    {
        // Init response
        $data = $this->client->getBorneId() ;
        return new JsonResponse($data, 200 );
    }
    #[Route('/json/borne/price', name: 'json_borne_price', methods: ['GET'])]
    public function getPrice(Request $request): JsonResponse
    {
        $connectorId = $request->get('idConnector');
        $borneId = $request->get('idBorne');
        // Init response
        $data = $this->client->getPriceFromApi($borneId,$connectorId) ;
        return new JsonResponse($data, 200 );
    }
    #[Route('/json/borne/start', name: 'json_borne_start', methods: ['POST'])]
    public function startCharge(Request $request, EmailService $emailService): JsonResponse
    {

        $borneId = $request->get('idBorne');
        $connectorId = $request->get('idConnector');
        $tagId = $request->get('idTag');
        $visualTag = $request->get('idVisualTag')? $request->get('idVisualTag') :'';
        // Init response
        $data = $this->client->startCharge($borneId,$connectorId,$tagId,$visualTag) ;
//        dump($data);
        if ( gettype($data)  !== 'string'){
            if ($data->status === 'Accepted'){
                $response = [
                    'message'=>'La charge a été lancée avec succès',
                    'success'=>true,
                    'data'=>$data,
                    'content'=> $this->renderView('borne/_borne_charging.html.twig', [])
                ];
            }else{
                $response = [
                    'message'=>'Une erreur est survenue',
                    'success'=>false,
                    'data'=>$data
                ];
            }
        }else{
            $response = [
                'message'=>'Une erreur est survenue',
                'success'=>false,
                'data'=>$data
            ];
        }

        return new JsonResponse($response, 200 );
    }
    #[Route('/json/borne/stop', name: 'json_borne_stop', methods: ['POST'])]
    public function stopCharge(Request $request, EmailService $emailService): JsonResponse
    {
        $transaction = $request->get('transaction');
        $email = $request->get('email')?$request->get('email'):'';
        // Init response
        $data = $this->client->stopCharge($transaction);
        if ($data->status === 'Accepted'){

//            $borneResponse = $this->client->request(Request::METHOD_GET, sprintf('api/charging-stations/%s', $borneId));
//            $borne = json_decode($borneResponse->getContent(), true);

            $response=[
                'message'=>"La charge a été stopée avec succès",
                'success'=>true,
                'data'=>$data,
                'transaction'=>$transaction,
                'content'=> $this->renderView('borne/_borne_start.html.twig', [])
                
            ];

        }else{
            $response=[
                'message'=>"Une erreur est survenue",
                'success'=>false,
                'data'=>$data
            ];
        }
        return new JsonResponse($response, 200 );
    }
    #[Route('/json/borne/view', name: 'json_borne_view', methods: ['GET'])]
    public function viewCharge(Request $request, EmailService $emailService): JsonResponse
    {

        $transaction = $request->get('transaction');
        // Init response
        try {
            $infoResponse = $this->client->request(Request::METHOD_GET, sprintf('/api/transactions/%s', $transaction));
            $info = json_decode($infoResponse->getContent(), true);
        } catch (\Exception $exception) {
            dd($exception);//TODO Error
        }
        $seconds = $info['currentTotalDurationSecs'];
        $time = sprintf('%02d:%02d:%02d', ($seconds/ 3600),($seconds/ 60 % 60), $seconds% 60);
        $response=[
                'message'=>"La charge a été stopée avec succès",
            'success'=>true,
            'data'=>$info,
            'content'=> $this->renderView('borne/_borne_info.html.twig', ['info'=>$info,'time'=>$time])
        ];
        return new JsonResponse($response, 200 );
    }
    #[Route('/json/borne/email', name: 'json_borne_email', methods: ['POST'])]
    public function email(Request $request, EmailService $emailService): JsonResponse
    {
        $data = [];
        $email = $request->get('email');
        if ($request->get('typeEmail')==='start'){
            $res = $emailService->startChargeEmail($email,[
                'id'=>$request->get('idBorne'),
                'connectorId'=>$request->get('idConnector'),
                'url'=>'http://'.$request->getHttpHost().'/borne/'.$request->get('idBorne'),
            ]);
            $data=[
                'transaction'=>$res['pin'],
            ];
        }else{
            $response = $emailService->stopChargeEmail($email,[
                'idCharge'=>$request->get('idTransaction'),
                'idBorne'=>$request->get('idBorne'),
            ]);

        }


        $response=[
            'message'=>"L'email a été envoyé avec succèes",
            'success'=>true,
            'data'=>$data
        ];
        return new JsonResponse($response, 200 );
    }
}
