from django.core.management.base import BaseCommand
import logging
import cv2  # OpenCV for handling RTSP streams
from myprofile.models import Camera
import json
from datetime import datetime
import time
import os
from django.conf import settings

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Logs the status of RTSP connections for all cameras'

    def handle(self, *args, **kwargs):
        while True:
            # Get all enabled cameras, ordered by creation date
            cameras = Camera.objects.filter(is_enabled=True).order_by('created_at')

            for camera in cameras:
                log_entry = self.log_camera_status(camera)
                # Write all log entries to the log file
                self.write_log_file(log_entry)
            time.sleep(300)

    def log_camera_status(self, camera):
        """
        Logs the status of a single camera's RTSP connection
        """
        log_entry = {
            'camera_id': camera.id,
            'camera_name': camera.camera_name,
            'time': datetime.now().isoformat(),
            'rtsp_url': camera.rtsp_url,
            'status': 'Failed',
            'message': '',
            'generated_date': str(datetime.now().date()),
        }

        try:
            # Try to open the RTSP stream
            cap = cv2.VideoCapture(camera.rtsp_url)
            if cap.isOpened():
                ret, _ = cap.read()
                if ret:
                    log_entry['status'] = 'Success'
                    log_entry['message'] = 'Camera connection successful.'
                else:
                    log_entry['message'] = f'Failed to read stream: {camera.rtsp_url}'
            else:
                log_entry['message'] = f'Failed to connect: {camera.rtsp_url}'
            cap.release()
        except Exception as e:
            log_entry['message'] = str(e)

        return log_entry

    def write_log_file(self, new_entries):
        """
        Write the log entries to a file in JSON format
        """
        log_file_path = os.path.join(settings.BASE_DIR, 'myprofile/logs', 'rtsp_logfile.json')

        # Load existing logs
        if os.path.exists(log_file_path):
            # Read the existing logs first
            with open(log_file_path, 'r+') as f:
                try:
                    existing_logs = json.load(f)
                except json.JSONDecodeError:
                    existing_logs = []
        else:
            existing_logs = []

        # Append new entries to existing logs
        existing_logs.append(new_entries)

        # Write all logs back to the file
        with open(log_file_path, 'w') as f:
                json.dump(existing_logs, f, indent=4)

        logger.info(f"Camera: {new_entries['camera_name']}, Status: {new_entries['status']}, Message: {new_entries['message']}")
