# -*- coding: utf-8 -*-

import urllib, urllib.parse, urllib.request
import re, os, xbmc, xbmcvfs, xbmcgui, time, calendar
import http.cookiejar as cookielib
import html
from .utils import log, get_content_from_response

class LightTitulkyClient(object):
    def __init__(self, username=None, password=None):
        self.server_url = 'https://www.titulky.com'
        self.username = username
        self.password = password
        self.cookies = {}
        
        # Inicilizace cookie jaru
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookielib.LWPCookieJar()))
        urllib.request.install_opener(self.opener)

    def login(self):
        """Přihlásí uživatele k serveru Titulky.com."""
        if not self.username:
            log("Client", "No username provided, proceeding as guest")
            return False
            
        log("Client", "Logging in to Titulky.com as %s" % self.username)
        login_postdata = urllib.parse.urlencode({
            'Login': self.username, 
            'Password': self.password, 
            'foreverlog': '0',
            'Detail2': ''
        }).encode("utf-8")
        
        request = urllib.request.Request(self.server_url + '/index.php', login_postdata)
        request.add_header('Origin', self.server_url)
        
        try:
            response = urllib.request.urlopen(request)
            content = get_content_from_response(response)
            
            if content.find('BadLogin') > -1:
                log("Client", "Login failed: Bad credentials")
                return False
                
            # Uložení cookies pro další požadavky
            set_cookie = response.getheader('Set-Cookie') or ""
            self.cookies['CRC'] = self._extract_cookie(set_cookie, 'CRC')
            self.cookies['LogonLogin'] = self._extract_cookie(set_cookie, 'LogonLogin')
            self.cookies['LogonId'] = self._extract_cookie(set_cookie, 'LogonId')
            
            log("Client", "Login successful")
            return True
        except Exception as e:
            log("Client", "Login error: %s" % e)
            return False

    def _extract_cookie(self, header, name):
        match = re.search(name + '=(\S+);', header, re.IGNORECASE)
        return match.group(1) if match else None

    def search(self, video_metadata):
        """Vyhledá titulky na základě metadat videa."""
        if video_metadata.get('custom_fulltext'):
            title = (video_metadata.get('custom_fulltext') or '').strip()
        elif video_metadata.get('tvshow'):
            title = "%s S%02dE%02d" % (
                video_metadata['tvshow'],
                int(video_metadata.get('season', 1)),
                int(video_metadata.get('episode', 1)),
            )
        else:
            title = (video_metadata.get('title', '') or '').strip()

        url = self.server_url + '/index.php?' + urllib.parse.urlencode({'Fulltext': title, 'FindUser': ''})
        log("Client", "Searching for: %s" % title)
        
        req = urllib.request.Request(url)
        req = self._add_cookies(req)
        
        try:
            response = urllib.request.urlopen(req)
            content = get_content_from_response(response)
            return self._parse_results(content)
        except Exception as e:
            log("Client", "Search error: %s" % e)
            return []

    def _parse_results(self, content):
        results = []
        # Parsování řádků tabulky s výsledky
        for row in re.finditer('<tr class=\"r(.+?)</tr>', content, re.IGNORECASE | re.DOTALL):
            try:
                data = row.group(1)
                item = {
                    'link_file': re.search('[^<]+<td[^<]+<a href=\"(?P<data>\S+).htm\"', data, re.IGNORECASE | re.DOTALL).group('data'),
                    'id': re.search('[^<]+<td[^<]+<a href=\"[\w-]+-(?P<data>\d+).htm\"', data, re.IGNORECASE | re.DOTALL).group('data'),
                    'title': re.search('[^<]+<td[^<]+<a[^>]+>(<div[^>]+>)?(?P<data>[^<]+)', data, re.IGNORECASE | re.DOTALL).group('data'),
                    'lang': 'Unknown'
                }
                
                # Detekce jazyka
                if 'alt="CZ"' in data: item['lang'] = 'Czech'
                elif 'alt="SK"' in data: item['lang'] = 'Slovak'
                
                # Verze / release
                version_match = re.search('title=\"(?P<data>[^\"]+)', data, re.IGNORECASE | re.DOTALL)
                item['version'] = version_match.group('data') if version_match else None
                
                results.append(item)
            except Exception:
                continue
        return results

    def download(self, sub_id, link_file, dest_dir):
        """Stáhne vybrané titulky."""
        # 1. Získání stránky pro stažení
        url = self.server_url + '/idown.php?' + urllib.parse.urlencode({
            'R': str(calendar.timegm(time.gmtime())),
            'titulky': sub_id,
            'histstamp': '',
            'zip': 'z'
        })
        
        req = urllib.request.Request(url)
        req.add_header('Referer', self.server_url + '/' + link_file + ".htm")
        req = self._add_cookies(req)
        
        response = urllib.request.urlopen(req)
        content = get_content_from_response(response)
        
        # 2. Kontrola čekacího času
        wait_time = 0
        wait_match = re.search('CountDown\((\d+)\)', content, re.IGNORECASE)
        if wait_match:
            wait_time = int(wait_match.group(1))
            log("Client", "Waiting %d seconds before download" % wait_time)
            for i in range(wait_time):
                xbmcgui.Dialog().notification("Titulky Light", "Čekám %d s..." % (wait_time - i), xbmcgui.NOTIFICATION_INFO, 1000)
                time.sleep(1)

        # 3. Získání odkazu k finálnímu stažení
        down_match = re.search('<a.+id=\"downlink\" href="([^\"]+)\"', content, re.IGNORECASE)
        if not down_match:
            log("Client", "Failed to find download link (maybe login expired or limit reached)")
            return None
            
        final_link = self.server_url + down_match.group(1)
        
        # 4. Samotné stažení
        req = urllib.request.Request(final_link)
        req.add_header('Referer', self.server_url + "/idown.php")
        req = self._add_cookies(req)
        
        zip_data = urllib.request.urlopen(req).read()
        
        dest_path = os.path.join(dest_dir, "titulky.zip")
        with open(dest_path, "wb") as f:
            f.write(zip_data)
            
        return dest_path

    def _add_cookies(self, request):
        if self.cookies:
            cookie_str = "; ".join(["%s=%s" % (k, v) for k, v in self.cookies.items() if v])
            request.add_header('Cookie', cookie_str)
        return request
