import traceback

import sentry_sdk
from django.db import models
from djconfig import config
from telegram import Bot, InputMediaPhoto
from vk_api import VkApi
from vk_api.audio import VkAudio
import vkwave

from feeds.models import FeedModuleConfig
from feeds.modules.utils import get_vk_photo, get_vk_audio
from feeds.utils import DatabaseConfig, captcha_handler


class VKFeedModuleConfig(FeedModuleConfig):
    owner_id = models.IntegerField()
    send_text = models.BooleanField(default=True)
    send_links = models.BooleanField(default=True)

    MODULE_NAME = 'VK feed'

    def execute(self, bot: Bot, chat_id, last_id):
        config._reload_maybe()

        if last_id is None:
            last_id = 0

        vk_session = VkApi(login=config.vk_username, password=config.vk_password, config=DatabaseConfig,
                           api_version='5.131', captcha_handler=captcha_handler)
        vk_session.auth()
        # vk_audio = VkAudio(vk_session)
        vk = vk_session.get_api()
        wall_data = vk.wall.get(owner_id=self.owner_id)
        for post in reversed(wall_data['items']):
            if post['id'] > last_id:
                try:
                    if self.send_text and post['text']:
                        bot.send_message(chat_id, post['text'])
                    if 'attachments' in post:
                        photos = []
                        for image in filter(lambda a: 'photo' in a, post['attachments']):
                            url = image['photo']['sizes'][-1]['url']
                            if url:
                                photos.append(url.replace('\\', ''))
                        if len(photos) == 1:
                            bot.send_photo(chat_id, photos[0])
                        elif len(photos) > 1:
                            bot.send_media_group(chat_id, [InputMediaPhoto(photo) for photo in photos])
                        # for a in post['attachments']:
                        #     if 'audio' in a:
                        #         f = get_vk_audio(vk_audio.get_audio_by_id(a['audio']['owner_id'], a['audio']['id']))
                        #         bot.send_audio(chat_id, f, None, a['audio'].get('artist'), a['audio'].get('title'))
                    if self.send_links:
                        bot.send_message(chat_id, f"https://vk.com/wall{post['owner_id']}_{post['id']}",
                                         disable_web_page_preview=True)
                except Exception as e:
                    sentry_sdk.capture_exception(e)
                    traceback.print_exc()
                yield post['id']
