import requests

from bs4 import BeautifulSoup
from collections import defaultdict
from .mongo_service import MongoService
from datetime import datetime


class CinestarService:
    movies_dictionary_list = []

    def __init__(self):
        pass

    def getDatesWithScreenings(self, cinema_id):
        url = (
                "https://www.cinestar.cz/cz/?option=com_csevents&task=DaysWithEvents.getEventDays&format=json&startDate=&cinema=%d&title=0" % cinema_id)
        response = requests.get(url=url).json()
        return response['data']

    def getcleanNameFromOptions(self, film_row):
        film_name = self.getFilmNameFromRow(film_row)
        film_name_options = ["TITULKY", "GC", "ATMOS", "3D", "DABING", "(Dámská jízda)", "ČSFD"]
        for option in film_name_options:
            if option in film_name:
                film_name = film_name.replace(option, '')
        return film_name

    def parseInformationFromName(self, film_name, options):
        found_information = []
        for option in options:
            if option in film_name:
                found_information.append(str(option).lower())
                film_name = film_name.replace(option, '')
        return found_information

    def getFilmNameFromRow(self, film_row):
        film_information = film_row.find('span', {'class': 'title'})
        return film_information.text

    def getScreeningLang(self, film_row):
        film_name = self.getFilmNameFromRow(film_row)
        film_name_lang_options = ["TITULKY", "DABING"]
        screening_lang = self.parseInformationFromName(film_name, film_name_lang_options)

        if len(screening_lang) == 0:
            play_param = film_row.find('span', {'class': 'play-param'})
            if (play_param is not None) and (("Titulky" in play_param.text) or ("Dabing" in play_param.text)):
                return {'screening_lang': 'en', 'screening_subt': 'cz'}
            else:
                return {'screening_lang': 'cz'}
        else:
            if len(screening_lang) == 1:
                if "titulky" in screening_lang[0]:
                    return {'screening_lang': 'en', 'screening_subt': 'cz'}
                else:
                    return {'screening_lang': 'cz'}
            else:
                raise ValueError('Found more then one information about screening language')

    def getScreeningOptions(self, film_row):
        film_name = self.getFilmNameFromRow(film_row)
        film_name_options = ["GC", "3D", "ATMOS", "(Dámská jízda)"]
        options = self.parseInformationFromName(film_name, film_name_options)
        if len(options) == 0:
            options.append('normal')
        return {'screening_type': options}

    def filmSkip(self, film_row):
        film_name = self.getFilmNameFromRow(film_row)
        film_name_options = ["opera", "BLINDBOX.CZ", "Scream for Me Sarajevo"]
        options = self.parseInformationFromName(film_name, film_name_options)
        if len(options) == 0:
            return False
        else:
            return True

    def setBasicDictionaryInformation(self, film_row, film_dictionary):

        name_dictionary = self.getFilmNameWithOptions(film_row)
        return {**film_dictionary, **name_dictionary}

    def isFilmDuplicate(self, film_dictionary):
        for film in self.movies_dictionary_list:
            if film_dictionary['film_name'] in film['film_name']:
                return film
        return None

    def parse_website(self, date, cinema):
        # TODO: For now until I sort out multi cinema duplicates

        self.movies_dictionary_list = []
        url = (
            "http://www.cinestar.cz/cz/?option=com_csevents&view=eventsforday&date={0}&cinema={1}&titleId=0&format=raw&tpl=program".format(
                date, cinema['cinema_id']))
        client = MongoService()
        dictionary_template = defaultdict()
        dictionary_template['Date'] = datetime.strptime(date,'%Y-%m-%d')
        dictionary_template['cinema_code'] = cinema['cinema_id']
        dictionary_template['cinema_company'] = 'cinestar'

        f = requests.get(url)
        soup = BeautifulSoup(f.content)

        for row in soup.find_all('tr'):
            film_row = row.find('td', {'class': 'tdTitle'})
            if film_row is not None:
                if self.filmSkip(film_row) is False:
                    film_dictionary = dictionary_template.copy()
                    film_dictionary['film_name'] = self.getcleanNameFromOptions(film_row)
                    film_duplicate = self.isFilmDuplicate(film_dictionary)
                    film_time_count = 0
                    if film_duplicate is not None:
                        film_dictionary = film_duplicate
                        film_time_count = len(film_dictionary['film_times'])
                    else:
                        film_dictionary['poster_url'] = film_row.find('img')['src']
                        film_dictionary['film_times'] = []
                    # film_name_options = self.setBasicDictionaryInformation(film_row)
                    screening_lang = self.getScreeningLang(film_row)
                    sreening_options = self.getScreeningOptions(film_row)

                    all_rows = row.find_all('td')
                    # TODO Try to simplify
                    for i in range(1, len(all_rows), 1):
                        if all_rows[i].find('span') is not None:
                            film_dictionary['film_times'].append(defaultdict(lambda: defaultdict()))
                            film_dictionary['film_times'][film_time_count].update(screening_lang)
                            film_dictionary['film_times'][film_time_count].update(sreening_options)
                            film_dictionary['film_times'][film_time_count]['cinema_name'] = cinema['name']

                            detail = all_rows[i].find('span')
                            # if all_rows[i].find('a') is None:
                            if detail.find('a') is None:
                                print(detail.next.strip())
                                film_dictionary['film_times'][film_time_count]['screening_start'] = (
                                    detail.next.strip())
                                film_dictionary['film_times'][film_time_count]['screening_room'] = \
                                    detail.find_all('em')[0].text
                                film_dictionary['film_times'][film_time_count]['screening_length'] = \
                                    detail.find_all('em')[
                                        1].text  # TODO KEEP ONLY DIGITS AND SAFE AS INT
                                film_dictionary['film_times'][film_time_count]['screening_end'] = detail.find_all('em')[
                                    2].text
                                film_time_count = film_time_count + 1
                            else:
                                print(detail.find('a').text)  # TIME OF Screening
                                film_dictionary['film_times'][film_time_count]['screening_start'] = detail.find(
                                    'a').text
                                film_dictionary['film_times'][film_time_count]['screening_buy_link'] = detail.find('a')[
                                    'href']
                                film_dictionary['film_times'][film_time_count]['screening_room'] = \
                                    detail.find_all('em')[0].text
                                film_dictionary['film_times'][film_time_count]['screening_length'] = \
                                    detail.find_all('em')[
                                        1].text  # TODO KEEP ONLY DIGITS AND SAFE AS INT
                                film_dictionary['film_times'][film_time_count]['screening_end'] = detail.find_all('em')[
                                    2].text
                                film_time_count = film_time_count + 1
                    if film_duplicate is None:
                        self.movies_dictionary_list.append(film_dictionary)
        print(dictionary_template)
        if len(self.movies_dictionary_list) != 0:
            client.saveCinemaInfo(self.movies_dictionary_list)
