<?php

namespace App\Http\Controllers;

use App\Helper\ApiHelper;
use Exception;
use Illuminate\Http\Request;
use MongoDB\Client as MongoDBClient;
use GuzzleHttp\Client;


class FrontController extends Controller
{
    protected $mongoDB;

    public function __construct(MongoDBClient $mongoDB)
    {

        $this->middleware('auth');
        $this->mongoDB = $mongoDB;
    }

    public function add_camera(Request $request)
    {
        $collection = $this->mongoDB->dataprocess->regions;
    }

    public function cameras($pageNumber, $regionid)
    {
        // $perPage = 50; // Number of documents per page
        // $page = request('page', $pageNumber); // Get the current page from the request, default to 1 if not provided

        // $skip = ($page - 1) * $perPage;

        $collection = $this->mongoDB->dataprocess->cameras;
        $cameras = $collection->find(
            [
                'region_id' => new \MongoDB\BSON\ObjectID($regionid)
            ],
            [
                'sort' => ['_id' => -1],
                //'skip' => $skip, // Skip the specified number of documents
                //'limit' => $perPage, // Limit the number of documents per page
            ]
        );
        return view("stream.cameras", compact('cameras', 'pageNumber'));
    }

    public function index()
    {
        $camera_info = $this->mongoDB->dataprocess->cameras;
        $collections = $this->mongoDB->dataprocess->regions;

        $result = $collections->find([], [
            'limit' => 6
        ]);

        $total_camera = $camera_info->countDocuments();
        $total_regions = $collections->countDocuments();


        $result = $collections->find([], [
            'limit' => 6
        ]);

        $regionsWithCameraCount = [];

        foreach ($result as $region) {
            // Count the number of cameras for each region
            $cameraCount = $this->mongoDB->dataprocess->cameras->count([
                'region_id' => $region->_id
            ]);

            // Add camera count to each region
            $region->camera_count = $cameraCount;
            $regionsWithCameraCount[] = $region;
        }
        // dd($regionsWithCameraCount);

        return view("main", compact('result', 'total_camera', 'total_regions', 'regionsWithCameraCount'));
        //return view("main");
    }

    public function cameras_details($camera_id)
    {
        $database = $this->mongoDB->framedata;
        //  $database->command(['ping'=>1]);
        $collection = $this->mongoDB->dataprocess->framedata;
        $cursor = $collection->find(
            ['camera_stream_id' => new \MongoDB\BSON\ObjectID($camera_id)],
            [
                'sort' => ['_id' => -1],
            ]
        );

        return view("stream.cameras_details", compact('cursor'));
    }

    public function AllRegions()
    {
        $collections = $this->mongoDB->dataprocess->regions;
        $result = $collections->find([]);
        return view("stream.regions_list", compact('result'));
        //return view("main");
    }

    public function faceDetections($frame_id)
    {
        //echo $frame_id .'';
        //die();
        $collection = $this->mongoDB->dataprocess->imagesinfo;

        $result = $collection->find(
            [
                'frame_id' => new \MongoDB\BSON\ObjectID($frame_id)
            ],
            [
                'sort' => ['_id' => -1]
            ]
        );

        return view("stream.faces_list", compact('result'));
    }

    public function view_main_frame($frame_id)
    {

        $data = null;
        //  return $frame_id;
        try {

            $collection = $this->mongoDB->dataprocess->framedata;
            $result = $collection->find(
                [
                    '_id' => new \MongoDB\BSON\ObjectID($frame_id)
                ]
            );

            if ($result) {
                foreach ($result as $key => $value) {
                    // echo json_encode($value);
                    $data = $value;
                }
                return view("frames.view_frame", compact('data'));
            }
            return response()->json(['error' => "Sorry try again", "status" => 204]);


        } catch (Exception $e) {
            return response()->json(['error' => "Sorry try again", "status" => 204]);
        }
    }

    public function getFaceFrameData($frame_id)
    {


        $collection_face_detect = $this->mongoDB->dataprocess->photo_face_detect;

        $result_face_detect = $collection_face_detect->findOne(
            [
                '_id' => new \MongoDB\BSON\ObjectID("$frame_id")
            ]
        );

        $faceInfo = $result_face_detect['info'];

        $collection_frame_detect = $this->mongoDB->dataprocess->photo_frame_detect;

        $result_frame_detect = $collection_frame_detect->findone(
            [
                '_id' => new \MongoDB\BSON\ObjectID($result_face_detect['main_frame_id'])
            ]
        );

        $videoPath = $result_frame_detect['fps_video_path'] ?? null;


        $list = null;
        //  return $frame_id;
        try {

            $collection = $this->mongoDB->dataprocess->imagesinfo;
            $result = $collection->find(
                [
                    '_id' => new \MongoDB\BSON\ObjectID($frame_id)
                ]
            );

            if ($result) {

                foreach ($result as $key => $value) {
                    // echo json_encode($value);
                    $list = $value;
                }

                return view("frames.view_face", compact('list', 'videoPath', 'faceInfo'));
                // return response()->json(['data' => $data , "status" => 200]);
            }
            return response()->json(['error' => "Sorry try again", "status" => 204]);


        } catch (Exception $e) {
            return response()->json(['error' => "Sorry try again", "status" => 204]);
        }
        //var_dump($result);
    }


    public function generate_video(Request $request)
    {
        $path = $request->path;



        $client = new Client();

        $response = ApiHelper::generate_frame_video($path);


        if($response != false && $response != "" && $response['error'] == false){

            // \Log::info($response['video_data']);

            // Return the response from the external API
            return $response['video_data'];
        }

        return "";

    }

}
