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

# edit 2025-09-29
import requests
requests.packages.urllib3.disable_warnings()
session = requests.Session()

from scrapers.modules.tools import cParser
from resources.lib.requestHandler import cRequestHandler
from scrapers.modules import cleantitle, dom_parser
from resources.lib.control import getSetting, setSetting
from resources.lib.utils import isBlockedHoster

SITE_IDENTIFIER = 'vhskassette'
SITE_DOMAIN = 'vhskassette.usite.pro'
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 = 'https://' + self.domain
        self.search_link = self.base_link + '/video/shv'
        self.sources = []

    def run(self, titles, year, season=0, episode=0, imdb=''):
        if season >= 1: return self.sources
        # -- login --
        username = getSetting('vhskassette.user')
        password = getSetting('vhskassette.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

        data = {
            'user': username,
            'password': password,
            'rem': '1',
            'a': '2',
            'ajax': '2',
            '_tp_': 'xml',
        }
        headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': 'https://vhskassette.usite.pro',
        }
        url = 'https://vhskassette.usite.pro/index/sub/'
        resp = session.post(url, data=data, headers=headers)
        # print(f'Status Code: {resp.status_code}')
        isMatch, aResult = cParser.parse(resp.text, "'(\?[^']+)")
        if isMatch: sReferer = self.base_link + '/' + aResult[0]
        else: return self.sources
        # ------ login end ------

        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('-', '')
                data = {
                    'query': sSearchText,
                    'c': ''
                }
                if '+' in sSearchText: data.update({'c': '70'})

                search_url = 'https://vhskassette.usite.pro/video/shv'
                get_resp = session.get(search_url, data=data)
                #print(f'Status Code: {get_resp.status_code}')
                sHtmlContent = get_resp.text
                pattern = '-preview.*?href="([^"]+).*?alt="([^"]+)'
                isMatch, aResult = cParser.parse(sHtmlContent, pattern)
                if not isMatch: continue
                for sUrl,sName  in aResult:
                    pattern_name = r'(.*?)(?:\s\(|\s\[)'
                    isMatch, name = cParser.parseSingleResult(sName, pattern_name)
                    pattern_year = r'(?:\(|\s)(\d{4})'
                    isMatch, sYear = cParser.parseSingleResult(sName, pattern_year)
                    pattern_quality = r'(?:\(|\s)(HD|OmU/HD)'
                    isMatch, sQuality = cParser.parseSingleResult(sName, pattern_quality)
                    if isMatch: sQuality = 'HD'
                    else: sQuality = 'SD'

                    if cleantitle.get(name) in t and int(sYear) == year:
                        if not sUrl in str(links):
                            links.append((sUrl,sQuality))
                    if len(links) > 0: break
                if len(links) > 0: break
            except:
                continue

        if len(links) == 0: return self.sources

        # showHosters
        for sUrl, sQuality in links:
            sUrl = self.base_link + sUrl
            aResult = []
            sHtmlContent = session.get(sUrl).text
            isMatch, sUrl = cParser().parse(sHtmlContent, 'class="link"[^>]href="([^"]+)')
            if isMatch:
                sHtmlContent2 = session.get(sUrl[0]).text
                isMatch, aResult = cParser().parse(sHtmlContent2, 'widget","([^"]+)')
                if not isMatch:
                    isMatch, aResult = cParser().parse(sHtmlContent2, '<iframe.src="([^"]+)')

            if not isMatch:
                isMatch, aResult = cParser().parse(sHtmlContent, 'ical.*?href="([^"]+)') #Dailymotion in Serien

            if isMatch:
                for sUrl in aResult:
                    if sUrl.startswith('//'):  sUrl = 'https:' + sUrl
                    isBlocked, hoster, url, prioHoster = isBlockedHoster(sUrl)
                    if isBlocked: continue
                    self.sources.append({'source': hoster, 'quality': sQuality, 'language': 'de', 'url': url, 'direct': True, 'prioHoster': prioHoster})

            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
                        isBlocked, hoster, url, prioHoster = isBlockedHoster(sUrl)
                        if isBlocked: continue
                        self.sources.append({'source': hoster, 'quality': sQuality, 'language': 'de', 'url': url, 'direct': True, 'prioHoster': prioHoster})

        return self.sources

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