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

__revision__ = '$Id: PluginMovieDVDfr.py 1410 2019-12-27 18:21:21Z edgrenoble $'

# Copyright (c) Ed Brandon
#
# 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

import string
import re
import gutils
import movie
from gettext import gettext as _

plugin_name         = "Dvdfr"
plugin_description  = "Dvdfr.com"
plugin_url          = "www.dvdfr.com"
plugin_language     = _("french")
plugin_author       = "Ed Brandon"
plugin_author_email = "<postmaster(at)edititionsbrandon.com>"
plugin_version      = "1.1"


class Plugin(movie.Movie):

    def __init__(self, id):
        self.encode   = 'utf-8'
        self.movie_id = id
        self.url      = "http://www.dvdfr.com/api/dvd.php?id=%s" % str(self.movie_id)

    def get_image(self):
        # Find the film's poster image
        tmp_poster = gutils.trim(self.page, "<cover>", "</cover>")
        if tmp_poster != "":
            self.image_url = "%s" % (tmp_poster)
        else:
            # tmp_poster = gutils.trim(self.page, "<cover>","</cover>")
            # if tmp_poster != "":
            #    self.image_url =
            #    "http://www.cinematografo.it/bancadati/images_locandine/%s/%s.jpg" % (self.movie_id, tmp_poster)
            #    self.image_url = tmp_poster
            # else:
            self.image_url = ""

    def get_o_title(self):
        # Find the film's original title
        self.o_title = gutils.trim(self.page, "<vo>", "</vo>")
        self.o_title = self.capwords(self.o_title)
        # if nothing found, use the title
        if self.o_title == '':
            self.o_title = gutils.trim(self.page, "<fr>", "</fr>")
        self.o_title = self.capwords(self.o_title)

    def get_title(self):
        # Find the film's local title.
        # Probably the original title translation
        self.title = gutils.trim(self.page, "<fr>", "</fr>")
        self.title = self.capwords(self.title)

    def get_director(self):
        # Find the film's director
        self.director = gutils.trim(self.page, "alisateur", "</star")
        self.director = gutils.after(self.director, ">")
        self.director = self.director.replace("&nbsp;&nbsp;", "&nbsp;")
        self.director = gutils.strip_tags(self.director)
        self.director = str.strip(self.director)

    def get_plot(self):
        # Find the film's plot
        self.plot = gutils.trim(self.page, "<synopsis>", "</synopsis>")

    def get_year(self):
        # Find the film's year
        self.year = gutils.trim(self.page, "<annee>", "</annee>")
        self.year = gutils.digits_only(gutils.clean(self.year))

    def get_runtime(self):
        # Find the film's running time
        self.runtime = gutils.trim(self.page, "<duree>", "</duree>")
        self.runtime = gutils.digits_only(gutils.clean(self.runtime))

    def get_genre(self):
        # Find the film's genre
        self.genre = gutils.trim(self.page, "<categories>", "</categories>")
        elements = str.split(self.genre, "<categorie>")
        self.genre = str.replace(self.genre, "<categorie>", "")
        self.genre = str.replace(self.genre, "</categorie>", ".")
        self.genre = str.replace(self.genre, "\n", "")
        self.number_results = elements[-1]

        if (elements[0] != ''):
            for element in elements:
                id = gutils.trim(element, "id>", "<")
                if id != '':
                    self.ids.append(id)
                    title = self.capwords(gutils.convert_entities(gutils.trim(element, "<fr>", "</fr>")))
                    year = re.search('([[][0-9]{4}[]])', element)
                    if year:
                        year = year.group(0)
                    if year:
                        self.titles.append(title + ' ' + year)
                    else:
                        self.titles.append(title)
        else:
            self.number_results = 0

    def get_cast(self):
        # Find the actors. Try to make it comma separated.
        self.cast_all = gutils.trim(self.page, "<stars>", '</stars>')
        self.cast_list = []
        while str.count(self.cast_all, "Acteur") != 0:
            self.cast_all = gutils.after(self.cast_all, "Acteur")
            self.cast_all = gutils.after(self.cast_all, ">")
            self.cast_next = gutils.before(self.cast_all, "</star")
            self.cast_list.append(self.cast_next)
            # self.cast = self.cast.append("\n")
            self.cast_all = gutils.after(self.cast_all, "</star>")
            self.cast = '\n'.join(self.cast_list)
    # self.cast = ""
    # self.cast_next = gutils.trim(
    # self.cast = self.cast.replace("target='_self'>", "\n>")
    # self.cast = self.cast.replace("<a>", _(" as ").encode('utf8'))
    # self.cast = self.cast.replace("</tr><tr>", '\n')
    # self.cast = self.cast.replace("...vedi il resto del cast", '')
    # self.cast = gutils.clean(self.cast)
    # self.cast = self.cast.replace("&nbsp;&nbsp;", ' ')
    # self.cast = re.sub('[ ]+', ' ', self.cast)
    # self.cast = re.sub('\n[ ]+', '\n', self.cast)

    # def get_classification(self):
        # Find the film's classification
        # self.classification = gutils.trim(self.page, "<reference>",
            # "</reference>")
        # self.classification = gutils.digits_only(gutils.clean(
            # self.classification))

    def get_studio(self):
        # Find the studio
        self.studio = self.capwords(gutils.clean(gutils.trim(self.page, "<studio>", "</studio>")))

    def get_o_site(self):
        # Find the film's oficial site
        self.o_site = self.capwords(gutils.clean(gutils.trim(self.page, "<url>", "</url>")))

    def get_site(self):
        # Find the film's imdb details page
        self.site = self.url

    def get_trailer(self):
        # Find the film's trailer page or location
        self.trailer = ''
        pos_end = str.find(self.page, '>guarda il trailer<')
        if pos_end > -1:
            pos_beg = self.page[:pos_end].rfind('<a href')
            if pos_beg > -1:
                self.trailer = gutils.trim(self.page[pos_beg:pos_end], '"', '"')

    def get_country(self):
        # Find the film's country
        self.country = str.replace(self.capwords(gutils.clean(gutils.after(gutils.trim(self.page, "<pays", "</pays>"),">"))), 'Usa', 'USA')

    def get_rating(self):
        # Find the film's rating. From 0 to 10.
        # Convert if needed when assigning.
        self.rating = 0

    def get_notes(self):
        self.notes = ''
        critica = gutils.clean(str.replace(gutils.regextrim(self.page, 'Critica</font>', "(</td>|\n|Note<)"), '<br>', '\n'))
        if critica:
            self.notes = 'Critica:\n\n' + critica + '\n\n'
        note = gutils.clean(str.replace(gutils.regextrim(self.page, 'Note</font>', "(</td>|\n|Critica<)"), '<br>', '--BR--'))
        if note:
            # string.capwords removes line breaks, preventing them with placeholder --BR--
            note = self.capwords(note)
            self.notes = self.notes + 'Note:\n\n' + str.replace(note, '--br--', '\n')
        tmp_poster = gutils.trim(self.page, "<cover>", "</cover>")
        self.notes = "\"%s\"" % tmp_poster

    def get_screenplay(self):
        # Find the screenplay
        self.screenplay_all = gutils.trim(self.page, "<stars>", '</stars>')
        self.screenplay_list = []
        while str.count(self.screenplay_all, "Scénariste") != 0:
            self.screenplay_all = gutils.after(self.screenplay_all, "Scénariste")
            self.screenplay_all = gutils.after(self.screenplay_all, ">")
            self.screenplay_next = gutils.before(self.screenplay_all, "</star")
            self.screenplay_list.append(self.screenplay_next)
            # self.screenplay = self.screenplay.append("\n")
            self.screenplay_all = gutils.after(self.screenplay_all, "</star>")
        self.screenplay = ','.join(self.screenplay_list)

    def get_cameraman(self):
        # Find the cameraman
        self.cameraman = gutils.trim(self.page, 'Fotografia</font></td></tr><tr>', '<td colspan="2"')
        self.cameraman = str.replace(self.cameraman, '<tr>', ', ')
        # beautification
        self.cameraman = gutils.clean(self.cameraman)
        self.cameraman = str.replace(self.cameraman, ' ,', ',')
        self.cameraman = re.sub('[ ]+', ' ', self.cameraman)
        self.cameraman = re.sub('[,][ ]*$', '', self.cameraman)

    def capwords(self, name):
        tmp = gutils.clean(name)
        if tmp == str.upper(tmp):
            return string.capwords(name)
        return name


class SearchPlugin(movie.SearchMovie):
    # print(self.title)
    # A movie search object
    def __init__(self):
        self.encode                = 'iso-8859-1'
        self.original_url_search   = 'http://www.dvdfr.com/api/search.php?title='
        self.translated_url_search = self.original_url_search

    def search(self, parent_window):
        # Perform the web search
        self.open_search(parent_window)
        # self.sub_search()
        return self.page

    # def sub_search(self):
    # Isolating just a portion (with the data we want) of the results
        #  self.page = gutils.trim(self.page, '<td valign="top" width="73%" bgcolor="#4d4d4d">', '</td>')

    def capwords(self, name):
        tmp = gutils.clean(name)
        if tmp == str.upper(tmp):
            return string.capwords(name)
        return name

    def get_searches(self):
        # Try to find both id and film title for each search result
        elements = str.split(self.page, "<dvd>")
        self.number_results = elements[-1]

        if elements[0] != '':
            for element in elements:
                id = gutils.trim(element, "id>", "<")
                if id != '':
                    self.ids.append(id)
                    title = self.capwords(gutils.convert_entities(gutils.trim(element, "<fr>", "</fr>")))
                    year = re.search('([[][0-9]{4}[]])', element)
                    if year:
                        year = year.group(0)
                    if year:
                        self.titles.append(title + ' ' + year)
                    else:
                        self.titles.append(title)
        else:
            self.number_results = 0
