from ..services.mongo_service import MongoService
from ..services.csfd_service import CsfdService
import datetime
import time


class Movie:
    mongo_service: MongoService
    film_list = []

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

    def findDuplicateFilm(self, film_name):
        # csfd = CsfdService(film_name)
        # name = csfd.getFilmTitle()
        for film in self.film_list:
            if str(film_name).strip().lower() in str(film['name']).strip().lower():
                return film
        return None

    # def mapCinemaCityFilm(self, film):
    #    return

    def mapCinestarFilm(self, film):
        dup = True
        film_dict = self.findDuplicateFilm(film['film_name'])
        if film_dict is None:
            csfd = CsfdService(film['film_name'])
            name = csfd.getFilmTitle()
            film_dict = self.findDuplicateFilm(name)
            if film_dict is None:
                dup = False
                film_dict = {
                    # 'test': film['film_name'],
                    'name': csfd.getFilmTitle(),
                    'genre': csfd.getFilmGenre(),
                    'description': csfd.getFilmDescription(),
                    'director': csfd.getFilmDirector(),
                    'actors': csfd.getActors(),
                    'ratings': csfd.getFilmRating(),
                    'release_date': csfd.getFilmReleaseDate(),
                    'screening_dates': []
                }
                if 'poster_url' in film:
                    film_dict['poster'] = film['poster_url']
                else:
                    film_dict['poster'] = csfd.getPosterUrl()
                self.isFilmReleased(film_dict)
        self.appendScreeningTimesToFilm(film, film_dict)
        if dup is False:
            self.film_list.append(film_dict)

    def createFilmObject(self):
        films = list(self.mongo_service.getAllScreenings())
        for film in films:
            print(film['film_name'])
            self.mapCinestarFilm(film)
        self.sortFilmByRating()
        self.sortScreenings()
        self.mongo_service.saveFilmList(self.film_list)

    def appendScreeningTimesToFilm(self, film, film_dict):
        date = film['Date']
        screening_to_append = None
        for screening in film_dict['screening_dates']:
            if date == screening['date']:
                screening_to_append = screening
        if screening_to_append is None:
            screening_to_append = {'date': film['Date'], 'screenings': film['film_times']}
            film_dict['screening_dates'].append(screening_to_append)
        else:
            screening_to_append['screenings'] = screening_to_append['screenings'] + (film['film_times'])

    def isFilmReleased(self, film_dict):
        today = datetime.date.today()
        film_release = film_dict['release_date'].date()
        if film_release > today:
            film_dict['released'] = False
        else:
            film_dict['released'] = True

    def sortScreenings(self):
        for i, film in iter(enumerate(self.film_list)):
            for j, screening_day in iter(enumerate(film['screening_dates'])):
                self.film_list[i]['screening_dates'][j]['screenings'] = sorted(screening_day['screenings'], key=self.getScreeningKey, reverse=False)
                # screenings_list = screening_day['screenings']
                # screenings_list.sort()

    def getScreeningKey(self, screening):
        start = screening['screening_start']
        start = start.replace(':','')
        return int(start)

    def sortFilmByRating(self):
        self.film_list = sorted(self.film_list, key=self.getKey, reverse=True)

    def getKey(self, movie):
        if (movie['ratings']) is None:
            return 0
        else:
            rating = movie['ratings'][0:2]
            return int(rating)
