<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Session\TokenMismatchException;
use Spatie\Permission\Exceptions\UnauthorizedException as SpatiePermissionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param Throwable $exception
     * @return void
     *
     * @throws Exception
     * @throws Throwable
     */
    public function report(Throwable $exception){
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  Request  $request
     * @param Throwable $exception
     * @return Response
     *
     * @throws Throwable
     */
    public function render($request, Throwable $exception){
        return parent::render($request, $exception);
    }


    public function registerV1(){

        $this->renderable(function (\Exception $exception,Request $request) {
            $handles = [
                NotFoundHttpException::class => [
                    "datas" => [
                        'title' => __("Page non trouvée"),
                        'message' => __("La page que vous demandez n'existe pas ou a été supprimé."),
                    ],
                    "status" => ServerStatus::NOT_FOUND,
                ],
//                RouteNotFoundException::class => [
//                    "datas" => [
//                        'title' => __("Page non trouvée"),
//                        'message' => __("La page que vous demandez n'existe pas ou a été supprimé."),
//                    ],
//                    "status" => ServerStatus::NOT_FOUND,
//                ],

                SpatiePermissionException::class => [
                    "datas" => [
                        'title' => __("Non Autorisé"),
                        'message' => __("Vous n'êtes pas autorisé à mener cette action."),
                    ],
                    "status" => ServerStatus::PERMISSION_DENIED,
                ],

                AuthenticationException::class => [
                    "datas" => [
                        'title' => __("Authentification Requise"),
                        'message' => __("Vous devez vous connecté pour continuer."),
                    ],
                    "status" => ServerStatus::AUTH_REQUIRED,
                ],

                TokenMismatchException::class => [
                    "datas" => [
                        'title' => __("Session Expiré"),
                        'message' => __("Votre session de navigation a expiré."),
                    ],
                    "status" => ServerStatus::CSFR_TOKEN_MISMATCH,

                ],

                ModelNotFoundException::class => [
                    "datas" => [
                        'title' => __("Ressource Introuvable"),
                        'message' => __("La ressource que vous demandez n'existe pas ou a été supprimé."),
                    ],
                    "status" => ServerStatus::APPLICATION_ERROR,
                ],

                AccessDeniedHttpException::class => [
                    "datas" => [
                        'title' => __("Non Autorisé"),
                        'message' => __("Vous n'êtes pas autorisé à mener cette action."),
                    ],
                    "status" => ServerStatus::PERMISSION_DENIED,
                ]

            ];

            $instance = get_class($exception); // "\Spatie\Permission\Exceptions\UnauthorizedException"

//            $datas = [
//                'title' => __("Erreur Interne"),
//                'message' => __("Une erreur imprévue est survenue lors de la demande."),
//            ];
            // $status = ServerStatus::APPLICATION_ERROR;

            // if ($exception instanceof AuthenticationException){}
            if (array_key_exists($instance,$handles)){
                $datas = $handles[$instance]['datas'];
                $status = $handles[$instance]['status'];
                if ($request->ajax() or $request->wantsJson()  or $request->is('api/*')){
                    return response()->json($datas, $status);
                }
                $view = "errors.$status";

                return response()->view($view, compact("datas",'status'));
            }else{
                if (app()->isProduction()){
                    if ($request->ajax() or $request->wantsJson() or  $request->is('api/*')){
                        return response()->json([
                            "datas" => [
                                'title' => __("Erreur interne du serveur"),
                                'message' => general_error(),
                            ],
                        ], ServerStatus::APPLICATION_ERROR);
                    }
                }

                if ($exception instanceof ModelNotFoundException){

                }
            }

        });

        // $this->reportable(function (Throwable $exception) {});
    }
}
