import requests
from .mongo_service import MongoService
from datetime import datetime


# tooltip: ex - executed, fn - film name, vn - venue, tm - time, ol - original language, vt - venue type,
# sb - subtitles, dt - date, db - dabing
class CinemacityService:
    cinema: dict
    cinemaUrl = ""
    movies_dictionary_list = []
    mongo_service: MongoService
    language_list = []
    venue_types = []

    def __init__(self, cinema):
        self.cinema = cinema
        self.mongo_service = MongoService()

    def getCinemacityMovieInfo(self):
        url = 'http://www.cinemacity.cz/upcommingJSON?includeVenueName=true&days=5&showExpired=true'
        response = requests.get(url=url).json()
        return response

    def getCinmacityMovieInfoForSpecificCinema(self, response):
        cinema = response['sites'][self.cinema['cinema_id']]
        self.cinemaUrl = cinema['tu']
        self.cinemaUrl = self.cinemaUrl.replace('token=$TOKEN$', '')
        return cinema

    def setListInformation(self, response):

        self.language_list = response['languages']
        self.venue_types = response['venueTypes']

    def syncCinemacityProgram(self):
        response = self.getCinemacityMovieInfo()
        self.setListInformation(response)
        movies = self.getCinmacityMovieInfoForSpecificCinema(response)['pr']
        self.saveProgramToDatabase(movies)
        return

    # def set

    def setBasicDictionaryStructure(self, movieDict):
        date = movieDict['dt'][0:10]
        dictionary = {
            'Date': datetime.strptime(date, '%d/%m/%Y'),
            'cinema_company': 'cinemacity',
            'cinema_code': self.cinema['cinema_id'],
            'cinemacity_id': movieDict['dc'],
            'film_name': movieDict['fn'], 'film_times': []}
        return dictionary

    def isFilmDuplicate(self, movieDict):
        for i, film in enumerate(self.movies_dictionary_list):
            if film['cinemacity_id'] == movieDict['dc']:
                return i
        return None

    def screeningInfo(self, movie):
        screening_dict = {'screening_start': movie['tm'],
                          'cinema_name': self.cinema['name']}
        venue = [self.venue_types[int(movie['vt'])]]
        if venue[0] is None:
            venue[0] = 'normal'
        screening_dict['screening_type'] = venue
        language = self.language_list[int(movie['ol'])]
        try:
            subtitles = movie['sb']
        except KeyError:
            subtitles = None
        try:
            dabing = movie['db']
        except KeyError:
            dabing = None

        if subtitles is not None and dabing is not None:
            raise ValueError('Film has both dabing and subtitles ')
        # 'READY' in movie['fn'] and '20:10' in movie['tm']

        if subtitles is None and dabing is not None:
            language = self.language_list[int(dabing)]
            if 'Česk' in language:
                screening_dict['screening_lang'] = 'cz'
            else:
                screening_dict['screening_lang'] = language
        elif subtitles is not None and dabing is None:
            subtitles_lang = self.language_list[int(subtitles)]
            if 'Angl' in language:
                screening_dict['screening_lang'] = 'en'
            else:
                screening_dict['screening_lang'] = language
            screening_dict['screening_subt'] = 'cz'
        else:
            # TODO - Deal with other lang
            if 'Česk' in language:
                screening_dict['screening_lang'] = 'cz'
            elif 'Angl' in language:
                screening_dict['screening_lang'] = 'en'
            else:
                screening_dict['screening_lang'] = language

        room = movie['vn']
        room = str(room).replace('Sál', '')
        if '4DX' in room:
            room = str(room).replace('4DX', '')
        screening_dict['screening_room'] = room
        ticketUrl = self.cinemaUrl + 'ec=' + movie['pc']
        screening_dict['screening_buy_link'] = ticketUrl
        return screening_dict

    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 filmSkip(self, film_name):
        film_name_options = ["- PŘEDPREMIÉRA PRO ČLENY KLUBU"]
        options = self.parseInformationFromName(film_name, film_name_options)
        if len(options) == 0:
            return False
        else:
            return True

    def saveProgramToDatabase(self, moviesList):
        for movie in moviesList:
            if self.filmSkip(movie['fn']) is False:
                # is_movie_duplicate = self.isFilmDuplicate(movie)
                film_dict = {}
                # if is_movie_duplicate is None:
                film_dict = self.setBasicDictionaryStructure(movie)
                self.movies_dictionary_list.append(film_dict)
                # else:
                #     film_dict = self.movies_dictionary_list[is_movie_duplicate]
                self.screeningInfo(movie)
                film_dict['film_times'].append(self.screeningInfo(movie))
        self.mongo_service.saveCinemaInfo(self.movies_dictionary_list)
