import logging
from rq import Queue
from datetime import datetime, timedelta
from archivingsystem.database import Database, ArchivedFile
from archivingsystem.retimestamping.retimestamper import retimestamping_task

log = logging.getLogger(__name__)

class Checker():
    def __init__(self, config: dict, q: Queue) -> None:
        self.config = config
        self.q = q
    
    def run(self):
        # Create database instance 
        # (this function is designed to run i separate 
        # process which needs own Database instance)
        db = Database(self.config)

        # Create database Session
        s = db.Session()

        # Get list of files to retimestamp (ArchivedFile is added if ExpirationDateTS is in less than 'days' days)
        files = s.query(ArchivedFile).filter(ArchivedFile.ExpirationDateTS < (datetime.now() + timedelta(days=self.config["archiving"]["timestamping"]["retimestamping"]["expiration"]))).all()

        # Push files to retimestamping queue
        log.info(f"Found {len(files)} files to be retimestamped")
        if len(files) > 0:
            for file in files:
                job = self.q.enqueue(retimestamping_task, self.config, file.FileID)
                log.debug(f"Task {job.id} added to {self.q.name} queue, with file ID {file}")
        log.info("Retimestamping check finished")