import os
from telegram.ext import ExtBot
from telegram.error import BadRequest
import logging
from datetime import time, timedelta, timezone, datetime, date
from peewee import fn
import models

CHAT_ID = os.getenv("CHAT_ID")


class SetChatPhotoJob():
    def __init__(self, bot: ExtBot, job_queue):
        self.bot = bot
        self.logger = logging.getLogger(self.__class__.__name__)
        
        if os.getenv("DOCKERIZED", "false") != "true":
            # when running locally, annoy the programmer every 60 seconds <3
            job_queue.run_repeating(self.callback_photo, interval=60)
        else:
            # set the message sending time; include UTC shift +2
            sending_time = time(hour=12, minute=0, second=0, tzinfo=timezone(timedelta(hours=2)))
            job_queue.run_monthly(self.callback_photo, when=sending_time, day=-1)


    async def callback_photo(self, context):
        
        # last_seen of memory must be older than 10 days in past or None
        with models.db:
            possible_photos = models.JournalEntry.select().where(
                models.JournalEntry.media_path != None
            ).order_by(fn.Random())
        
            try:
                chosen_entry = possible_photos.get()
            except:
                self.logger.warning("No photos available.")
                return

        chat_id = os.getenv("CHAT_ID")
        try:
            await self.bot.set_chat_photo(chat_id, chosen_entry.media_path)
        except BadRequest:
            self.logger.error("This is a private chat!")
            return