import re

import feedparser
from telegram import Bot
from telegram.constants import MAX_CAPTION_LENGTH

from feeds.models import FeedModuleConfig


IMAGE_RE = re.compile(r'<img alt=".+?" height=".+?" src="(.+?)" title')
CAPTION_RE = re.compile(r'<div>(<p>.*?</p>)</div>')
CAPTION_NEWLINE_RE = re.compile(r'(\w*<p>|</p>\w*){1,2}')


class NerfNowFeedModuleConfig(FeedModuleConfig):
    MODULE_NAME = 'NerfNow.com'

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

        feed = feedparser.parse('http://feeds.feedburner.com/nerfnow/full')
        for e in reversed(feed['entries']):
            if e['feedburner_origlink'] > last_id:
                data = e['content'][0]['value'].replace('\n', '')
                url = IMAGE_RE.search(data).group(1).replace('/large', '')
                comment = CAPTION_NEWLINE_RE.sub('\n', CAPTION_RE.search(data).group(1))
                comment = comment.replace('<br />', '')
                caption = '<b>{}</b>\n\n{}\n\n{}'.format(e['title'], comment, e['feedburner_origlink'])
                if len(caption) <= MAX_CAPTION_LENGTH:
                    bot.send_photo(chat_id, url, caption, parse_mode='html')
                else:
                    m = bot.send_photo(chat_id, url)
                    bot.send_message(chat_id, caption, parse_mode='html', reply_to_message_id=m.message_id)
                yield e['feedburner_origlink']
