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

# edit 2024-12-14

try:
    from resources.lib.utils import help, isBlockedHoster
except:
    from xbmc import executebuiltin
    executebuiltin('Quit')
    exit()

from scrapers.modules.tools import cParser
from resources.lib.requestHandler import cRequestHandler
from scrapers.modules import cleantitle, source_utils
from resources.lib.control import getSetting, setSetting, quote_plus, quote
#from resources.lib.utils import isBlockedHoster

SITE_IDENTIFIER = 'flimmerstube'
SITE_DOMAIN = 'flimmerstube.com'
SITE_NAME = SITE_IDENTIFIER.upper()

class source:
    def __init__(self):
        self.priority = 1
        self.language = ['de']
        self.domain = getSetting('provider.' + SITE_IDENTIFIER + '.domain', SITE_DOMAIN)
        self.base_link = 'http://' + self.domain
        self.search_link = self.base_link + '/video/shv'
        self.sources = []

    def run(self, titles, year, season=0, episode=0, imdb='', hostDict=None):
        username = getSetting('flimmerstube.user')
        password = getSetting('flimmerstube.pass')
        if username == '' or password == '':
            import xbmcgui, xbmcaddon
            AddonName = xbmcaddon.Addon().getAddonInfo('name')
            xbmcgui.Dialog().ok(AddonName,
                                "In den Einstellungen die Kontodaten (Login) für %s eintragen / überprüfen\nBis dahin wird %s von der Suche ausgeschlossen. Es erfolgt kein erneuter Hinweis!" % (
                                    SITE_NAME, SITE_NAME))
            setSetting('provider.' + SITE_IDENTIFIER, 'false')
            return self.sources
        try:
            oRequest = cRequestHandler('http://flimmerstube.com/index/sub/')
            oRequest.cacheTime = 60 * 60 * 24
            oRequest.addHeaderEntry('X-Requested-With', 'XMLHttpRequest')
            oRequest.addHeaderEntry('Referer', self.base_link)
            oRequest.addParameters('user', username)
            oRequest.addParameters('password', password)
            oRequest.addParameters('rem', '1')
            oRequest.addParameters('a', '2')
            oRequest.addParameters('ajax', '2')
            oRequest.addParameters('_tp_', 'xml')
            resp = oRequest.request()
            # http://flimmerstube.com/?l2whwf
            isMatch, aResult = cParser.parse(resp, "'(\?[^']+)")
            if isMatch: sReferer = self.base_link + '/' + aResult[0]
            else: return self.sources

            t = set([cleantitle.get(i) for i in set(titles) if i])
            links = []
            for sSearchText in titles:
                try:
                    if ','in sSearchText: sSearchText=sSearchText.replace(',','')
                    if '-' in sSearchText: sSearchText = sSearchText.replace('-', '')
                    #sSearchText = quote_plus(sSearchText)
                    oRequest = cRequestHandler(self.search_link)
                    oRequest.cacheTime = 60 * 60 * 6  # 6 Stunden
                    oRequest.addHeaderEntry('Referer', sReferer)
                    oRequest.addHeaderEntry('Upgrade-Insecure-Requests', '1')
                    oRequest.addParameters('query', sSearchText)
                    if '+' in sSearchText:
                        oRequest.addParameters('c', '70')
                    else:
                        oRequest.addParameters('c', '')

                    sHtmlContent = oRequest.request()
                    pattern = 've-screen"\s+title="([^"]+).*?href="([^">]+)'  # inklusive sYear
                    isMatch, aResult = cParser.parse(sHtmlContent, pattern)
                    if not isMatch: continue
                    #total = len(aResult)
                    for sName, sUrl in aResult:
                        # TODO
                        if sName.startswith('('): sQuality = 'HD'
                        else: sQuality = 'SD'
                        #     isQuality, sQuality = cParser.parse(sName, '\((\D+)[\)]')
                        #     if isQuality: isQuality, sQuality = cParser.parse(sName, 'HD')
                        for k in (('(HD)', ''), ('(OmU/HD)', '')):  # Ausblenden der Elemente im sName vorne
                            sName = sName.replace(*k)
                        isNameYear, sNameYear = cParser.parse(sName, '(.*?)\((\d*)\)')  # Jahr und Name trennen
                        sName, sYear = sNameYear[0]
                        if season == 0:
                            if cleantitle.get(sName) in t and int(sYear) == year:
                                if not sUrl in str(links):
                                    links.append((sUrl,sQuality))
                        else:
                            print(sName)
                        if len(links) > 0: break
                except:
                    continue

            if len(links) == 0: return self.sources
            for url, sQuality in links:  # showHosters
                sUrl = self.base_link + url
                aResult = []
                sHtmlContent = cRequestHandler(sUrl).request()
                isMatch, sUrl = cParser().parse(sHtmlContent, 'class="link"[^>]href="([^"]+)')
                if isMatch:
                    sHtmlContent2 = cRequestHandler(sUrl[0]).request()
                    isMatch, aResult = cParser().parse(sHtmlContent2, 'p><iframe.*?src="([^"]+)')
                    if 'bowfile' in aResult[0]:  # Wenn Hoster bowfile ist, dann in Container nach dem HD File suchen und direkt ohne Resolver abspielen, siehe getHosterUrl
                        sHtmlContent3 = cRequestHandler(aResult[0]).request()
                        isMatch, aResult = cParser().parse(sHtmlContent3, 'mp4HD:.?"([^"]+)')
                        import xbmcgui, xbmcaddon
                        AddonName = xbmcaddon.Addon().getAddonInfo('name')
                        xbmcgui.Dialog().ok(AddonName, "Info an Entwickler - Flimmerstube überprüfen - Film benennen")

                if isMatch:
                    for sUrl in aResult:
                        if sUrl.startswith('//'):  sUrl = 'https:' + sUrl
                        valid, hoster = source_utils.is_host_valid(sUrl, hostDict)
                        if not valid: continue
                        self.sources.append({'source': hoster, 'quality': sQuality, 'language': 'de', 'url': sUrl, 'direct': False})

                        #hoster = {'link': sUrl, 'name': cParser.urlparse(sUrl)}
                        #hosters.append(hoster)
                if not isMatch:
                    pattern = 'vep-title.*?</h1.*?src=.*?http..([\S]+)'
                    isMatch, aResult = cParser.parse(sHtmlContent, pattern)
                    if isMatch:
                        for sUrl in aResult:
                            if sUrl.startswith('//'):  sUrl = 'https:' + sUrl
                            valid, hoster = source_utils.is_host_valid(sUrl, hostDict)
                            if not valid: continue
                            self.sources.append({'source': hoster, 'quality': sQuality, 'language': 'de', 'url': sUrl, 'direct': False})

            return self.sources
        except:
            return self.sources

    def resolve(self, url):
        try:
            return url
        except:
            return
