from app.config.extensions import db

from app.models.spot import Spot
from app.models.channel import Channel
from app.models.program import Program
from app.models.base import TimestampedMixin


class DetectedSpot(TimestampedMixin): 
    """
    Represents a detected spot during TV monitoring.
    """
    spot = db.ReferenceField(
        Spot, 
        help_text="Reference to the detected spot."
    )
    channel = db.ReferenceField(
        Channel, 
        help_text="Reference to the channel where the spot was detected."
    )
    program = db.ReferenceField(
        Program, 
        help_text="Name of the program or show during which the spot was detected."
    )
    air_date = db.DateTimeField(
        required=True, 
        help_text="Date when the spot was aired."
    )
    start_time = db.DateTimeField(
        required=True,
        help_text="Start time of the detected spot."
    )
    end_time = db.DateTimeField(
        required=True,
        help_text="End time of the detected spot."
    )
    metadata = db.DictField(
        help_text="Additional metadata about the detected spot (e.g., tags, notes)."
    )
    stream_part = db.StringField(
        max_length=255,
        help_text="Part of the stream where the spot was detected (e.g., pre-roll, mid-roll, post-roll)."
    )
    frames_from_live = db.ListField(
        db.StringField(),
        help_text="List of frames captured from the live broadcast during the spot detection."
    )
    verified = db.BooleanField(
        default=False,
        help_text="Verification status of the detected spot."
    )

    meta = {
        'collection': 'detected_spots',  
    }

    def __str__(self):
        return f"DetectedSpot {self.id} - Program: {self.program}, Channel: {self.channel}, Air Date: {self.air_date}"

    def __repr__(self):
        return f"<DetectedSpot {self.id}>"

    def toggle_is_verified(self):
        self.is_verified = not self.is_verified
        return self.is_verified
    
    def to_dict(self):
        """
        Convert the document to a dictionary.
        """
        document_dict = super(DetectedSpot, self).to_dict() 
        # Remove any '_cls' field
        document_dict.pop('_cls', None)
        # Remove any '_id' field
        document_dict.pop('_id', None)
        # Replace 'id' field with 'public_id' field
        document_dict["public_id"] = document_dict.pop('id', None) 
        # Convert datetime objects to ISO 8601 strings
        document_dict['air_date'] = self._format_datetime(document_dict.get('air_date'))
        document_dict['start_time'] = self._format_datetime(document_dict.get('start_time'))
        document_dict['end_time'] = self._format_datetime(document_dict.get('end_time')) 
        # 
        return document_dict