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

__revision__ = '$Id'

# Written by Wolfgang Friebel <wp.friebel@gmail.com>
# Copyright (©) 2025 Wolfgang Friebel
# based on latest version of PluginMovieIMDB.py, V. Nunes, P. Ożarowski
#
# 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 gutils
import movie
import re
import logging
from bs4 import BeautifulSoup

plugin_name         = 'Kino.de'
plugin_description  = 'KINO.DE'
plugin_url          = 'www.kino.de'
plugin_language     = _('Deutsch')
plugin_author       = 'W. Friebel'
plugin_author_email = '<wp.friebel@gmail.com>'
plugin_version      = '1.30'

log = logging.getLogger('Griffith')

class Plugin(movie.Movie):

    def __init__(self, id):
        self.page_main = None
        self.encode='utf-8'
        self.movie_id = id
        self.url = self.movie_id
        self.soup = None
        self.details = {}

    def initialize(self):
        self.page_main = self.open_page(url=self.url)
        self.soup = BeautifulSoup(self.page_main, 'html.parser')

    def get_details(self, item):
        dict = {'regie': '', 'actors': ''}
        if (not self.details):
            elements = self.soup.find_all('ul',{'class': 'product-list-inline'})
            for element in elements:
                key = ''
                for li in element.find_all('li'):
                    if (li.text.strip() == 'Regie:'):
                        key = 'regie'
                        continue
                    if (li.text.strip() == 'Besetzung:'):
                        key = 'actors'
                        continue
                    if (key):
                        if (len(li.text.strip()) > 2):
                            dict[key] = dict[key] + li.text.strip()
                        continue
                    if (re.findall(r'/www.kino.de/filme/genres/',str(li))):
                        dict['genres'] = li.text.strip()
                    if (re.findall(r'/www.kino.de/filme/laender/',str(li))):
                        dict['laender'] = li.text.strip()
                    if (re.findall(r'^FSK ', li.text)):
                        dict['freigabe'] = li.text.strip()
                    if (re.findall(r'\b\d+\b Min\b', li.text)):
                        dict['laufzeit'] = int(re.findall(r'\d+',li.text)[0])
            self.details = dict
        if (item in self.details):
            return self.details[item]
        else:
            return ''

    def get_details2(self, item):
        str = ''
        elements = self.soup.find_all('h5',{'class': 'mb-0'})
        for element in elements:
            if (item in element.text):
                content = element.next_sibling
                for i in content.find_all('li'):
                    str = str + i.text.strip()
                return str
        
    def get_image(self):
        image = self.soup.find('meta', {'property': 'og:image'})
        self.image_url = image['content']

    def get_o_title(self):
        title = self.soup.find('meta', {'property': 'og:title'})
        self.o_title = title['content'].strip()

    def get_title(self):
        title = self.soup.find('meta', {'property': 'og:title'})
        self.title = title['content'].strip()

    def get_director(self):
        self.director = self.get_details('regie')

    def get_plot(self):
        article = self.soup.find('div',{'class': 'alice-layout-article-body'})
        self.plot = article.find('p',{'class': 'mb-3'}).text

    def get_year(self):
        self.year = self.url[-5:-1].isdigit()

    def get_runtime(self):
        self.runtime = self.get_details('laufzeit')

    def get_genre(self):
        self.genre = self.get_details('genres')

    def get_cast(self):
        actors = self.get_details2('Darsteller')
        if (not actors):
            actors = self.get_details('actors')
        self.cast = actors.replace(',', '\n')

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

    def get_studio(self):
        self.studio = ''

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

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

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

    def get_country(self):
        self.country = self.get_details('laender')

    def get_rating(self):
        rating = self.soup.find('span', {'class': 'rating-modal-detail-count'}, {'data-index': 5})
        self.rating = int(re.findall(r'\d+',rating.text)[0])/10

    def get_notes(self):
        self.notes = ''

    def get_screenplay(self):
        self.screenplay = self.get_details2('Drehbuch')

    def get_cameraman(self):
        self.cameraman = self.get_details2('Kamera')

class SearchPlugin(movie.SearchMovie):

    def __init__(self):
        #super().__init__()
        self.original_url_search = 'https://www.kino.de/se/?searchterm=%s&types=movie'
        self.translated_url_search = 'https://www.kino.de/se/?searchterm=%s&types=movie'
        self.encode='utf-8'
        self.remove_accents = False
        self.page = None


    def search(self,parent_window):
        if not self.open_search(parent_window):
            return None
        #return self.page
        pagemovie = self.page
        #
        # Sub Pages
        #
        pagesarea = gutils.trim(pagemovie, 'class="pagination-prev', '</ol>')
        pagelements = re.split('href="', pagesarea)
        self.title = ''
        self.o_title = ''
        for index in range(1, len(pagelements), 1):
            pagelement = pagelements[index]
            self.url = gutils.before(pagelement, '"')
            self.open_search(parent_window)
            if self.page:
                pagemovie = pagemovie + gutils.trim(self.page, '<ul>', '</ul>')
        self.page = pagemovie

        return self.page

    def get_searches(self):
        soup = BeautifulSoup(self.page, 'html.parser')

        elements = soup.find_all('a', {'class': 'alice-teaser-link'})
        for element in elements:
            url = element['href']
            if url[0] == '/':
                url = "https:" + url
            year = url[-5:-1]
            title = element.text.strip()
            if year.isdigit():
                title = title + ' - ' + year
            self.ids.append(url)
            self.titles.append(title)
#
# Plugin Test
#
class SearchPluginTest(SearchPlugin):
    #
    # Configuration for automated tests:
    # dict { movie_id -> [ expected result count for original url, expected result count for translated url ] }
    #
    test_configuration = {
        'Rocky Balboa'         : [ 10, 10 ],
        'Arahan'               : [ 10, 10 ],
        'Ein glückliches Jahr' : [ 4, 4 ]
    }

class PluginTest:
    #
    # Configuration for automated tests:
    # dict { movie_id -> dict { arribute -> value } }
    #
    # value: * True/False if attribute only should be tested for any value
    #        * or the expected value
    #
    test_configuration = {
        'K_rocky-balboa/96132.html' : {
            'title'               : 'Rocky Balboa',
            'o_title'             : 'Rocky Balboa',
            'director'            : 'Sylvester Stallone',
            'plot'                : True,
            'cast'                : 'Sylvester Stallone' + _(' as ') + 'Rocky Balboa\n\
Antonio Traver' + _(' as ') + 'Mason "The Line" Dixon\n\
Burt Young' + _(' as ') + 'Paulie\n\
Geraldine Hughes' + _(' as ') + 'Marie\n\
Milo Ventimiglia' + _(' as ') + 'Rocky Jr.\n\
James Francis Kelly III' + _(' as ') + 'Steps\n\
Tony Burton' + _(' as ') + 'Duke\n\
A.J. Benza' + _(' as ') + 'L.C.',
            'country'             : 'USA',
            'genre'               : 'Drama',
            'classification'      : '12',
            'studio'              : 'Fox',
            'o_site'              : False,
            'site'                : 'http://www.kino.de/kinofilm/rocky-balboa/96132.html',
            'trailer'             : 'http://www.kino.de/kinofilm/rocky-balboa/trailer/96132.html',
            'year'                : 2007,
            'notes'               : False,
            'runtime'             : 102,
            'image'               : True,
            'rating'              : False,
            'cameraman'           : 'J. Clark Mathis',
            'screenplay'          : 'Sylvester Stallone'
        },
        'K_ein-glueckliches-jahr/28675.html' : {
            'title'               : 'Ein glückliches Jahr',
            'o_title'             : 'La bonne année',
            'director'            : 'Claude Lelouch',
            'plot'                : True,
            'cast'                : 'Lino Ventura\n\
Françoise Fabian\n\
Charles Gérard\n\
André Falcon',
            'country'             : 'Frankreich/Italien',
            'genre'               : 'Drama',
            'classification'      : '12',
            'studio'              : 'Columbia TriStar',
            'o_site'              : False,
            'site'                : 'http://www.kino.de/kinofilm/ein-glueckliches-jahr/28675.html',
            'trailer'             : 'http://www.kino.de/kinofilm/ein-glueckliches-jahr/trailer/28675.html',
            'year'                : 1973,
            'notes'               : False,
            'runtime'             : 115,
            'image'               : True,
            'rating'              : False,
            'cameraman'           : 'Jean Collomb',
            'screenplay'          : 'Claude Lelouch'
        },
        'V_ein-glueckliches-jahr-dvd/85546.html' : {
            'title'               : 'Ein glückliches Jahr',
            'o_title'             : 'La bonne année',
            'director'            : 'Claude Lelouch',
            'plot'                : True,
            'cast'                : 'Lino Ventura\n\
Françoise Fabian\n\
Charles Gérard\n\
André Falcon',
            'country'             : 'Frankreich/Italien',
            'genre'               : 'Drama',
            'classification'      : 'ab 12',
            'studio'              : 'Black Hill Pictures',
            'o_site'              : False,
            'site'                : 'http://www.video.de/videofilm/ein-glueckliches-jahr-dvd/85546.html',
            'trailer'             : False,
            'year'                : 1973,
            'notes'               : 'Sprachen:\n\
Deutsch DD 2.0, Französisch DD 2.0\n\
\n\
Tonformat:\n\
Dolby Digital 2.0\n\
\n\
Bildformat:\n\
1:1,33/4:3',
            'runtime'             : 110,
            'image'               : True,
            'rating'              : False,
            'cameraman'           : 'Jean Collomb',
            'screenplay'          : 'Claude Lelouch'
        },
        'V_arahan-vanilla-dvd/90405.html' : {
            'title'               : 'Arahan',
            'o_title'             : 'Arahan jangpung dae jakjeon',
            'director'            : 'Ryoo Seung-wan',
            'plot'                : True,
            'cast'                : 'Ryu Seung-beom' + _(' as ') + 'Sang-hwan\n\
Yoon So-yi' + _(' as ') + 'Wi-jin\n\
Ahn Sung-kee' + _(' as ') + 'Ja-woon\n\
Jung Doo-hong' + _(' as ') + 'Heuk-woon\n\
Yun Ju-sang' + _(' as ') + 'Mu-woon',
            'country'             : 'Südkorea',
            'genre'               : 'Action/ Komödie',
            'classification'      : 'ab 16',
            'studio'              : 'Splendid Film',
            'o_site'              : False,
            'site'                : 'http://www.video.de/videofilm/arahan-vanilla-dvd/90405.html',
            'trailer'             : False,
            'year'                : 2004,
            'notes'               : 'Sprachen:\n\
Deutsch DD 5.1\n\
\n\
Tonformat:\n\
Dolby Digital 5.1\n\
\n\
Bildformat:\n\
1:1,78/16:9',
            'runtime'             : 108,
            'image'               : True,
            'rating'              : False,
            'cameraman'           : 'Lee Jun-gyu',
            'screenplay'          : 'Ryoo Seung-wan'
        }
    }
