import requests
from bs4 import BeautifulSoup
from datetime import datetime

class CsfdService:
    csfd_url = 'https://www.csfd.cz/'
    film_page: BeautifulSoup

    def __init__(self, film_name):
        film_href = self.selectFilmFromSearch(film_name)
        url = self.csfd_url + film_href
        req = requests.get(url)
        self.film_page = BeautifulSoup(req.content, "lxml")

    def selectFilmFromSearch(self, film_name):
        search_url = self.csfd_url + 'hledat/?q={0}'.format(film_name)
        req = requests.get(search_url)
        soup = BeautifulSoup(req.content, "lxml")
        search_div = soup.find('div', {'id': 'search-films'})
        if search_div is None:
            return 'hledat/?q={0}'.format(film_name)
        li = search_div.find('li')
        return li.find('a')['href']

    def getFilmTitle(self):
        div = self.film_page.find('div',{'id': 'profile'})
        return str(div.find('h1').text).strip()

    def getFilmGenre(self):
        div = self.film_page.find('div', {'id': 'profile'})
        return str(div.find('p', {'class': 'genre'}).text).strip()

    def getFilmDirector(self):
        div = self.film_page.find('div', {'id': 'profile'})
        span = div.find('span', {'itemprop': 'director'})
        return str(span.find('a').text).strip()

    def getActors(self):
        div = self.film_page.find('div', {'id': 'profile'})
        creators_section = div.find('div', {'class': 'creators'})
        creators = creators_section.findAll('div')
        for creator in creators:
            if 'Hrají' in creator.text:
                actors = creator.findAll('a')
                return_actors = []
                for i, actor in enumerate(actors):
                    if i == 2:
                        break
                    return_actors.append(actor.text)
                return return_actors
        return []
        raise AssertionError("Didn't find actors in on the page")

    def getFilmRating(self):
        rating = str(self.film_page.find('h2', {'class': 'average'}).text)
        if rating is '':
            rating = None
        return rating

    def getPosterUrl(self):
        div = self.film_page.find('div', {'id': 'poster'})
        return 'https:' + str(div.find('img')['src']).strip()

    def getFilmDescription(self):
        div = self.film_page.find('div', {'id': 'plots'})
        return str(div.find('li').text).strip()

    def getFilmReleaseDate(self):
        div = self.film_page.find('div', {'id': 'releases'})
        for tr in div.findAll('tr'):
            if tr.find('img', {'title': 'Česko'}) is not None:
                date_str = str(tr.find('td').text).strip()[0:10]  # To take only the date from it not publisher
                return datetime.strptime(date_str, '%d.%m.%Y')


