from app.config.extensions import db

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


class Schedule(TimestampedMixin):
    """
    Schedule Model

    Represents a schedule of TV programs in the application. 

    Attributes: 

    Methods:
        to_dict(): Convert the document to a dictionary.

    Meta:
        collection (str): The name of the MongoDB collection to store the documents.
    """
 
    # Channel on which the schedule is set
    channel = db.ReferenceField(
        Channel,
        help_text="Reference to the channel."
    )
    # Program scheduled during this time
    program = db.ReferenceField(
        Program,
        help_text="Reference to the program scheduled."
    )
    # Date of the schedule
    date = db.DateTimeField(
        required=True,
        help_text="Date of the program schedule."
    )
    # Start time of the schedule
    start_time = db.DateTimeField(
        required=True,
        help_text="Start time of the program."
    )
    # End time of the schedule
    end_time = db.DateTimeField(
        required=True,
        help_text="End time of the program."
    )

    def __str__(self):
        return f"TV Schedule: {self.channel.name} {self.program.name} {self.date} "

    def __repr__(self):
        return f"< TV Schedule(channel={self.channel.name}, program={self.program.name}, date={self.date}, ) >"

    def to_dict(self):
        """
        Convert the document to a dictionary.
        """ 
        document_dict = super(Schedule, self).to_dict()   
        # Remove any '_cls' field
        document_dict.pop('_cls', None) 
        # Remove any '_id' field
        document_dict.pop('_id', None)
        # Remove any '_id' field
        document_dict.pop('id', None)
        # replace id field with public id field
        document_dict["id"] =  document_dict.pop('public_id', None) 
        # Convert datetime objects to ISO 8601 strings 
        document_dict['date'] = self._format_datetime(document_dict.get('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  
        
    meta = {
        'collection': 'schedule'
    }