import requests
from django.db import models
from telegram import Bot

from feeds.models import FeedModuleConfig


class WPComicFeedModuleConfig(FeedModuleConfig):
    domain = models.URLField()

    MODULE_NAME = 'WordPress comic'

    def execute(self, bot: Bot, chat_id, last_id):
        if last_id is None:
            last_id = 0

        media = requests.get('{}/wp-json/wp/v2/media'.format(self.domain.rstrip('/'))).json()
        for m in filter(lambda x: x['id'] > last_id, reversed(media)):
            bot.send_photo(chat_id, photo=m['source_url'], caption=m['title']['rendered'])
            yield m['id']