# -*- coding: UTF-8 -*-

__revision__ = '$Id$'

# Copyright (c) 2018 John Cheetham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

# You may use and distribute this software under the terms of the
# GNU General Public License, version 2 or later


# This plugin was based on PluginMovieMovieMeter.py by Michael Jahn

import movie
import tmdbsimple as tmdb
import re
from gettext import gettext as _

plugin_name         = 'TMDb'
plugin_description  = 'The Movie Database'
plugin_url          = 'www.themoviedb.org'
plugin_language     = _('English')
# API key created for Griffith
tmdb.API_KEY = '426f7c7cf85d924909a867c00376f1e4'

class Plugin(movie.Movie):

    def __init__(self, id):
        self.encode   = 'utf8'
        self.movie_id = id
        # only for user visible url field, fetching is based on the XML RPC API
        self.url      = "https://www.themoviedb.org/"

    def open_page(self, parent_window=None, url=None):
        self.movie_info = None
        self.movie_credits = None
        self.config_info = None
        if parent_window is not None:
            self.parent_window = parent_window
        self.progress.set_data(parent_window, _("Fetching data"), _("Wait a moment"), False)
        self.progress.pulse()
        try:
            self.movie = tmdb.Movies(int(self.movie_id))
            self.movie_info = self.movie.info()
            self.movie_credits = self.movie.credits()
            self.configuration = tmdb.Configuration()
            self.config_info = self.configuration.info()
            self.progress.pulse()
        finally:
            self.progress.pulse()
        return True

    def get_image(self):
        try:
            self.image_url = self.config_info['images']['base_url']
            self.image_url += self.config_info['images']['still_sizes'][0]
            self.image_url += self.movie_info['poster_path']
        except Exception:
            self.image_url = ''

    def get_o_title(self):
        self.o_title = self.movie_info['original_title']

    def get_title(self):
        self.title = self.movie_info['title']

    def get_director(self):
        self.director = ''
        for element in self.movie_credits['crew']:
            if element['job'] == 'Director':
                self.director = self.director + element['name'] + ', '
        self.director = re.sub(', $', '', self.director)

    def get_screenplay(self):
        self.screenplay = ''
        for element in self.movie_credits['crew']:
            if element['job'] == 'Screenplay':
                self.screenplay = self.screenplay + element['name'] + ', '
        self.screenplay = re.sub(', $', '', self.screenplay)

    def get_plot(self):
        self.plot = self.movie_info['overview']

    def get_year(self):
        self.year = self.movie_info['release_date']

    def get_runtime(self):
        self.runtime = self.movie_info['runtime']

    def get_genre(self):
        self.genre = ''
        for element in self.movie_info['genres']:
            self.genre = self.genre + element['name'] + ' | '
        self.genre = re.sub(' \| $', '', self.genre)

    def get_cast(self):
        self.cast = ''
        for element in self.movie_credits['cast']:
            self.cast = self.cast + element['name'] + _(' as ') + element['character'] + '\n'

    def get_classification(self):
        self.classification = ''

    def get_studio(self):
        self.studio = ''
        for element in self.movie_info['production_companies']:
            self.studio = self.studio + element['name'] + ', '
        self.studio = re.sub(', $', '', self.studio)

    def get_o_site(self):
        self.o_site = ''

    def get_site(self):
        self.site = ''

    def get_trailer(self):
        self.trailer = ''

    def get_country(self):
        self.country = ''
        for element in self.movie_info['production_countries']:
            self.country = self.country + element['name'] + ', '
        self.country = re.sub(', $', '', self.country)

    def get_rating(self):
        try:
            self.rating = round(float(self.movie_info['popularity']))
        except Exception:
            self.rating = 0

    def get_notes(self):
        self.notes = ''
        languages = _('Language') + ': '
        i = 0
        for element in self.movie_info['spoken_languages']:
            if i > 0:
                languages += ' | '
            languages += element['name']
            i += 1
        self.notes = self.notes + languages + '\n'
        self.notes = self.notes + _('Tagline') + ': ' + self.movie_info['tagline']

class SearchPlugin(movie.SearchMovie):

    def __init__(self):
        self.original_url_search   = 'https://www.themoviedb.org/'
        self.translated_url_search = 'https://www.themoviedb.org/'
        self.encode                = 'utf8'

    def search(self,parent_window):
        self.result_array = None
        if not self.open_search(parent_window):
            return None
        if self.result_array:
            return 'dummy'
        return None

    def open_search(self, parent_window):
        self.titles = [""]
        self.ids = [""]
        if parent_window is not None:
            self.parent_window = parent_window
        self.progress.set_data(parent_window, _("Searching"), _("Wait a moment"), False)
        self.progress.pulse()
        self.progress.pulse()
        try:
            search = tmdb.Search()
            search.movie(query=self.title)
            self.result_array = search.results
            self.progress.pulse()
        finally:
            self.progress.pulse()
        return True

    def get_searches(self):
        for element in self.result_array:
            self.ids.append(element['id'])
            try:
                release_date = element['release_date']
            except Exception:
                release_date = '?'
            self.titles.append(element['title'] + ' (' + release_date + ')')
