# -*- coding: utf-8 -*-

import re
from datetime import datetime
from time import mktime
from bs4 import BeautifulSoup
from pymongo import MongoClient, DESCENDING
from config import MONGODB_URI

class EchoParser:
    @staticmethod
    def _get_participants(html):
        soup = BeautifulSoup(html, 'html.parser')
        guests = []
        contributors = []
        paragraphs = soup.find_all('p')
        for tag in paragraphs:
            if 'Гости' in tag.text:
                raw_guests = tag.find_all('a')
                for guest in raw_guests:
                    guest_url = guest['href'].strip()
                    guest_name = guest.text.strip()
                    guests.append(
                        dict(
                            name=guest_name,
                            url=guest_url,
                        )
                    )
            if 'Ведущие' in tag.text:
                raw_contributors = tag.find_all('a')
                for cont in raw_contributors:
                    cont_url = cont['href'].strip()
                    cont_name = cont.text.strip()
                    contributors.append(
                        dict(
                            name=cont_name,
                            url=cont_url
                        )
                    )
        return guests, contributors

    @staticmethod
    def parse_item_avatar(html):
        soup = BeautifulSoup(html, 'html.parser')
        img_url = ''
        img = soup.find('img')
        if img:
            img_url = img['src']
        return img_url

    @staticmethod
    def parse_exact_title(title):
        result = re.search(r'(^.*):', title)
        return result.group(1).strip()

    def parse_item(self, item):
        radio_show = dict()
        if 'id' not in item:
            return None

        radio_show['media_id'] = item.get('id')
        radio_show['duration'] = item.get('itunes_duration')
        published_dt = datetime.fromtimestamp(mktime(item.get('published_parsed')))
        radio_show['published'] = str(published_dt)
        radio_show['guests'], radio_show['contributors'] = self._get_participants(item.get('summary', ''))
        radio_show['title'] = item.get('title', '').replace(u'\xa0', u' ')
        radio_show['avatar'] = self.parse_item_avatar(item.get('summary', ''))
        radio_show['program'] = self.parse_exact_title(radio_show['title'])
        radio_show['enclosure'] = item.enclosures[0]
        if 'links' in item:
            links = item['links']
            radio_show['url'] = ''.join([link.get('href') for link in links if link.get('rel') == 'alternate'])
            radio_show['audio'] = ''.join([link.get('href') for link in links if link.get('rel') == 'enclosure'])
        return radio_show

    @staticmethod
    def _save(item):
        client = MongoClient(MONGODB_URI)
        db = client.echo_feed
        radio_shows = db['radio_shows']
        radio_shows.update_one(
            {'media_id': item['media_id']},
            {"$set": item},
            upsert=True
        )

    def save(self, item):
        self._save(item)

    @staticmethod
    def get():
        client = MongoClient(MONGODB_URI)
        db = client.echo_feed
        radio_shows = db['radio_shows']
        cursor = radio_shows.find({}, {"_id": 0}).sort('published', DESCENDING)
        return [show for show in cursor]
