# -*- coding: utf-8 -*-
try:
    from lib.dns import CloudflareHTTP
except ImportError:
    from dns import CloudflareHTTP
import re
import json

def parselist(url):
    iptv = []
    try:
        r = CloudflareHTTP.get(url, timeout=4)
        if r and 'response' in r:
            res = r['response']
            url = res.json()['url']
    except:
        pass
    try:
        if 'paste.kodi.tv' in url and not 'documents' in url and not 'raw' in url:
            try:
                key = url.split('/')[-1]
                url = 'https://paste.kodi.tv/documents/' + key
                r = CloudflareHTTP.get(url, timeout=4)
                if r and 'response' in r:
                    res = r['response']
                    src = res.json()['data']
                    servers = json.loads(src)
                    for i in servers:
                        host = i['host']
                        mac = i['mac']
                        iptv.append((host,mac))

                    
            except:
                pass
        else:
            try:
                r = CloudflareHTTP.get(url, timeout=4)
                if r and 'response' in r:
                    res = r['response']
                    servers = res.json()
                    for i in servers:
                        host = i['host']
                        mac = i['mac']
                        iptv.append((host,mac))
            except:
                pass                   
    except:
        pass
    return iptv


class StalkerAPI:
    def __init__(self,hostname,mac):
        self.hostname = hostname
        self.mac_address = mac
        self.session = CloudflareHTTP
        self.token = self.get_token(self.session, self.hostname, self.mac_address)

    def get_token(self, session, url, mac_address):
        try:
            url = url + "/portal.php?type=stb&action=handshake&JsHttpRequest=1-xml"
            cookies = {"mac": mac_address, "stb_lang": "en", "timezone": "Europe/London"}
            headers = {"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C)"}
            response = session.get(url, cookies=cookies, headers=headers, timeout=4)
            r = response['response']
            token = r.json()["js"]["token"]
            #token = response.json()["js"]["token"]
            if token:
                return token
        except:
            return ''


    def get_channels(self, session, url, mac_address, token, category_type, category_id):
        try:
            channels = []
            cookies = {"mac": mac_address, "stb_lang": "en", "timezone": "Europe/London"}
            headers = {"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C)", "Authorization": "Bearer " + token}

            if category_type == 'IPTV':
                page_number = 1
                while True:
                    url = "{}/portal.php?type=itv&action=get_ordered_list&genre={}&force_ch_link_check=&fav=0&sortby=number&hd=0&p={}&JsHttpRequest=1-xml&from_ch_id=0".format(url, category_id, page_number)
                    response = session.get(url, cookies=cookies, headers=headers, timeout=4)
                    response = response['response']
                    if response.status_code == 200:
                        try:
                            response_json = response.json()
                            channels_data = response_json["js"]["data"]
                           
                            channels.extend(channels_data)
                            total_items = response_json["js"]["total_items"]
                            max_page_items = response_json["js"]["max_page_items"]
                            if len(channels) >= total_items:
                                break
                            page_number += 1
                        except ValueError:
                            #print("Invalid JSON format in response")
                            break
                    else:
                        #print(f"IPTV Request failed for page {page_number}")
                        break

            # elif category_type == 'VOD' or category_type == 'Series':
            #     page_number = 1
            #     while True:
            #         url = f"{url}/server/load.php?type={category_type.lower()}&action=get_ordered_list&category={category_id}&genre={category_id}&p={page_number}&JsHttpRequest=1-xml"
            #         response = session.get(url, cookies=cookies, headers=headers)
            #         if response.status_code == 200:
            #             try:
            #                 response_json = response.json()
            #                 channels_data = response_json["js"]["data"]
            #                 print(channels_data)
                            
            #                 channels.extend(channels_data)
            #                 total_items = response_json["js"]["total_items"]
            #                 max_page_items = response_json["js"]["max_page_items"]
            #                 if len(channels) >= total_items:
            #                     break
            #                 page_number += 1
            #             except ValueError:
            #                 print("Invalid JSON format in response")
            #                 break
            #         else:
            #             print(f"{category_type} Request failed for page {page_number}")
            #             break

           
            # Clear the model before adding new items
            # self.model.clear()
            
            # Add channels to the model
            # for channel in channels:
            #     channel_name = channel['name']
            #     print(channel_name)
            return channels
        
        except Exception as e:
            #print(f"An error occurred while retrieving channels: {str(e)}")
            return []
        
    def get_genres(self, session, url, mac_address, token):
        try:
            url = url + "/portal.php?type=itv&action=get_genres&JsHttpRequest=1-xml"
            cookies = {"mac": mac_address, "stb_lang": "en", "timezone": "Europe/London"}
            headers = {"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C)", "Authorization": "Bearer " + token}
            response = session.get(url, cookies=cookies, headers=headers, timeout=4)
            response = response['response']            
            genre_data = response.json()["js"]
            if genre_data:
                genres = []
                for i in genre_data:
                    gid = i["id"]
                    name = i["title"]
                    genres.append({'name': name, 'category_type': 'IPTV', 'genre_id': gid})
                return genres
        except:
            pass

    def listar_categoria(self):
        new_genres = []
        genres = self.get_genres(self.session,self.hostname,self.mac_address,self.token)
        if genres:
            for i in genres:
                name = i.get('name','')
                category_type = i.get('category_type', 'IPTV')
                genre_id = i.get('genre_id', '')
                if name and category_type and genre_id:
                    if not 'all' in name.lower():
                        new_genres.append({'name': name, 'category_type': category_type, 'genre_id': genre_id})
                        #new_genres.append((name,category_type,genre_id))
        return new_genres

    def selecionar_categoria(self,category_type,category_id):
        new_channels = []
        channels = self.get_channels(self.session, self.hostname, self.mac_address, self.token, category_type, category_id)
        if channels:
            for i in channels:
                channel_name = i.get('name', '')
                channel_url = i.get('cmd', '')
                iconimage = i.get('logo', '')
                if channel_name and channel_url:
                    new_channels.append({'name': channel_name, 'url': channel_url, 'iconimage': iconimage})
                    #new_channels.append((channel_name, channel_url, iconimage))
        return new_channels

    def create_link(self,cmd):
        try:
            session = self.session
            url = '{}/portal.php?type=itv&action=create_link&cmd={}&series=&forced_storage=undefined&disable_ad=0&download=0&JsHttpRequest=1-xml'.format(self.hostname, cmd)
            cookies = {"mac": self.mac_address, "stb_lang": "en", "timezone": "Europe/London"}
            headers = {"User-Agent": "Mozilla/5.0 (QtEmbedded; U; Linux; C)", "Authorization": "Bearer " + self.token}
            response = session.get(url, cookies=cookies, headers=headers, timeout=4)
            response = response['response']            
            channel_url=re.findall('"cmd":"ffmpeg (.*?)"',response.text )[0]
            channel_url=channel_url.replace("\\", "")
        except:
            channel_url = ''
        return channel_url 

    def get_stream(self,cmd): # play iptv stalker
        #http://localhost/ch/135912_
        if str(cmd).startswith("ffmpeg "):
            cmd = cmd[len("ffmpeg "):]
        stream = self.create_link(cmd)
        if not 'extension' in stream:
            stream = stream + '&extension=m3u8'
        else:
            stream = stream.replace('&extension=ts', '&extension=m3u8')
        return stream                             
                                    