<?php

namespace App\Helper;

use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;


class HelperData
{

    public static $FACE_MATCHING_URL_FACE_FIND = "http://192.168.9.121:5004/findface";
    public static $FACE_MATCHING_URL_FIND_DATA = "http://192.168.9.121:5004/finddata";

    static function  convertTimeStamp($timestampMilliseconds)
    {
        $created_at_timestamp = $timestampMilliseconds->toDateTime()->getTimestamp(); // Convert BSON date to UNIX timestamp
        // Create a DateTime object using the timestamp
        $created_at = (new \DateTime())->setTimestamp($created_at_timestamp);
        // Format the date to a specific format (e.g., 'Y-m-d H:i:s')
        return $formatted_created_at = $created_at->format('Y-m-d H:i:s');
        
    }

    static function  isStreamGood($url)
    {
        $data = explode(":", $url);
        $cameraIP = $data[0];
        $cameraPort = $data[1];

        if (!HelperData::checkCameraAvailability($cameraIP, $cameraPort)) {
            return 505;
        }

        return  200;
    }

    static function isValidURL($inputUrl)
    {
        try {
            // Use filter_var with FILTER_VALIDATE_URL
            if (filter_var($inputUrl, FILTER_VALIDATE_URL) === false) {
                return false;
            } else {
                return true;
            }
        } catch (\Exception $e) {
            // Error 
            return false;
        }
    }
    static function isURLDNS($url)
    {
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); // Set a timeout for the connection

        $response = curl_exec($curl);

        if ($response === false) {
            // cURL error occurred
            // echo 'cURL error: ' . curl_error($curl);
            return false;
        } else {
            // Successful cURL request
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            if ($httpCode === 200) {
                return true;
            } else {
                return false;
            }
        }

        curl_close($curl);
    }

    static function isURLVideoStream($url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); // Set a timeout for the connection
        curl_setopt($curl, CURLOPT_TIMEOUT, 5); // Set a timeout of 10 seconds
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');

        $response = curl_exec($curl);

        if ($response === false) {
            // cURL error occurred
            // echo 'cURL error: ' . curl_error($curl);
            return false;
        } else {
            // Successful cURL request
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            if ($httpCode === 200) {
                $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
                return true;
                // Check if the Content-Type indicates video content
                // if (strpos($contentType, 'video/') !== false) {
                //     return true;
                // } else {
                //     return false;
                // }
            } else {
                return false;
            }
        }

        curl_close($curl);
    }

    static function checkCameraAvailability($ip, $port, $timeout = 5)
    {
        $socket = @fsockopen($ip, $port, $errno, $errstr, $timeout);

        if (!$socket) {
            return false; // Unable to establish a connection
        }

        fclose($socket);
        return true; // Connection successful
    }


    static function isCameraStreaming($streamUrl, $timeout = 5)
    {
        // Set stream context timeout
        $context = stream_context_create(['http' => ['timeout' => $timeout]]);

        // Attempt to read data from the camera stream URL
        $streamData = @file_get_contents($streamUrl, false, $context);

        // Check if data was successfully retrieved
        if ($streamData === false) {
            return false; // Unable to retrieve stream data
        }
        // Check if the stream data is not empty and appears to be video data
        // Check if the stream data includes video-related headers
        $videoHeaders = ['Content-Type: video', 'Content-Type: application/octet-stream'];
        foreach ($videoHeaders as $header) {
            // echo strpos($streamData, $header);
            if (strpos($streamData, $header) !== false) {
                return true; // Video-related headers found, indicating an active stream
            }
        }

        return false; // Stream data is empty
    }



    // Example usage:
    static function isVideoContent($data)
    {
        // You can use more advanced checks here, e.g., using FFmpeg or analyzing the data content
        // This example checks if the received data contains common video file headers
        $videoHeaders = ['\x00\x00\x00\x18', 'ftypisom', 'moov', 'mdat'];

        foreach ($videoHeaders as $header) {
            if (strpos($data, $header) !== false) {
                return true;
            }
        }

        return false;
    }

    static function humanReadableFileSize($bytes, $decimals = 2) {
        $size = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . ' ' . $size[$factor];
    }
  
}
