# -*- coding: utf-8 -*-
"""
The local database module
SPDX-License-Identifier: MIT
"""

# pylint: disable=too-many-lines,line-too-long
import xbmc
import platform
import json
import time
import hashlib
import xml.etree.ElementTree as ET
from .akfw import utils as pyUtils
from .akfw import webResource as WebResource

from urllib.parse import urlencode, urljoin

class DpGronkhTv(object):
    """
    API Requests
    """

    def __init__(self, pAddon):
        self._addon = pAddon
        self.logger = pAddon.createLogger('DpGronkhTv')
        self.abortHook = pAddon.getAbortHook()
        self.profilePath = pAddon.getAddonDataPath()     
        self.kodiPG = pAddon.getProgressDialog()
        self.starttime = time.time()
        #
        self.apiUrlSearch = 'https://backend.gronkh.tv/v3/videos/search'; # Options: ?first=24&direction=desc&sort=date
        self.apiUrlNewest = 'https://backend.gronkh.tv/v3/videos/discovery/newest'
        self.apiUrlRandom = 'https://backend.gronkh.tv/v3/videos/discovery/random'
        self.apiUrlHot = 'https://backend.gronkh.tv/v3/videos/discovery/hot'
        self.apiUrlVideoPlaylist = 'https://backend.gronkh.tv/v3/videos/episode' # Options: /<episodeid>
        self.apiUrlTags = 'https://backend.gronkh.tv/v3/tags'
        #
        version = xbmc.getInfoLabel("System.BuildVersion").split(" ", 1)
        machine = platform.machine() # x86_64
        os_name = platform.system()  # Linux, Windows ...
        self.userAgent = f"Kodi/{version[0]} ({os_name} {machine}) plugin.video.gronkhtv-Addon  Version/{version[0]}-{version[1].replace(' ', '-')}"
        #
        self.itemsPerPage = 24
        self.itemsPerPageNew = 8
        self.itemsPerPageMost = 8

    def getNewStreams(self):
        self.logger.debug('getNewStreams')
        streamliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadNewest())
            # self.logger.debug('datajson {}', data)
            #
            videos = pyUtils.extractJsonValue(data, 'data')
            if videos:
                for video in videos:
                    # self.logger.debug('video: {}', video)
                    streamliste.append(video)
            else:
                self.logger.error('Could not find key "data" in JSON. Data: ', data)
        #
        except Exception as err:
            self.logger.error('getNewStreams {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return streamliste

    def getHotStreams(self):
        self.logger.debug('getHotStreams')
        streamliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadHot())
            # self.logger.debug('datajson {}', data)
            #
            videos = pyUtils.extractJsonValue(data, 'data')
            if videos:
                for video in videos:
                    # self.logger.debug('video: {}', video)
                    streamliste.append(video)
        #
        except Exception as err:
            self.logger.error('getHotStreams {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return streamliste
    
    def getRandomStreams(self):
        self.logger.debug('getRandomStreams')
        streamliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadRandom())
            # self.logger.debug('datajson {}', data)
            #
            videos = pyUtils.extractJsonValue(data, 'data')
            if videos:
                for video in videos:
                    # self.logger.debug('video: {}', video)
                    streamliste.append(video)
        #
        except Exception as err:
            self.logger.error('getRandomStreams {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return streamliste

    def getStreamByTag(self, tagid):
        self.logger.debug('getStreamsByTag')
        streamliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadSearch(
                page = 1,
                direction = "desc",
                order = "created_at",
                tags=tagid
            ))
            self.logger.debug('datajson {}', data)
            #
            videos = pyUtils.extractJsonValue(data, 'data')
            if videos:
                for video in videos:
                    # self.logger.debug('video: {}', video)
                    streamliste.append(video)
            else:
                self.logger.error('Could not find key "data" in JSON. Data: ', data)
        #
        except Exception as err:
            self.logger.error('getStreamsByTag {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return streamliste

    def getAllTags(self):
        self.logger.debug('getAllTags')
        tagliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadTags())
            self.logger.debug('datajson {}', data)
            tagliste = data['data']
        #
        except Exception as err:
            self.logger.error('getAllTags {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return tagliste

    def getStreamsPaginated(self, page = 1):
        self.logger.debug('getStreamsPaginated')
        streamliste = []
        self.kodiPG.create(30010)
        if page < 1:
            page = 1
        self.logger.debug('getStreamsPaginated - Loading Page {}', page)
        lastepisode = 0
        try:
            data = json.loads(self.loadSearch(
                page = page,
                direction = "desc",
                order = "created_at",
            ))
            # self.logger.debug('datajson {}', data)
            #
            videos = pyUtils.extractJsonValue(data, 'data')
            if videos:
                for video in videos:
                    # self.logger.debug('video: {}', video)
                    streamliste.append(video)
                    if video['episode'] < lastepisode or lastepisode == 0:
                        lastepisode = video['episode']
            else:
                self.logger.error('Could not find key "data" in JSON. Data: ', data)

            if page < data['meta']['last_page']:
                streamliste.append({
                    'nextlink': True,
                    'episode': (lastepisode - 1),
                    'page': (page + 1)
                })
        #
        except Exception as err:
            self.logger.error('getStreamsPaginated {}', err)
            self.kodiPG.close()
            raise

        

        # Test if next page exists
        # nextpage = page + 1
        # self.logger.debug('getStreamsPaginated - Test Page {}', nextpage)
        # try:
        #     data = json.loads(self.loadSearch(
        #         page = nextpage,
        #         direction = "desc",
        #         order = "created_at",
        #     ))
        #     # self.logger.debug('datajson {}', data)
        #     #
        #     videos = pyUtils.extractJsonValue(data, 'data')
        #     self.logger.debug('videos in test {}', videos)
        #     if videos and len(videos) > 0:
        #         # Next Page exists
        #         streamliste.append({
        #             'nextlink': True,
        #             'episode': (lastepisode - 1),
        #             'page': nextpage
        #         })
        #     else:
        #         self.logger.error('Could not find key "data" in JSON. Data: ', data)
        # #
        # except Exception as err:
        #     self.logger.error('getStreamsPaginated {}', err)
        #     self.kodiPG.close()
        #     raise
        # #
        self.kodiPG.close()
        return streamliste


    def loadNewest(self):
        dn = WebResource.WebResource(
            self._addon,
            self.apiUrlNewest,
            pUseragent=self.userAgent
        )

        return dn.retrieveAsString()

    def loadRandom(self):
        dn = WebResource.WebResource(
            self._addon,
            self.apiUrlRandom,
            pUseragent=self.userAgent
        )

        return dn.retrieveAsString()

    def loadHot(self):
        dn = WebResource.WebResource(
            self._addon,
            self.apiUrlHot,
            pUseragent=self.userAgent
        )

        return dn.retrieveAsString()

    def loadSearch(self, page = 1, direction = "desc", order = "created_at", tags = None):
        # Possible dir: asc, desc
        # Possible order: created_at, meta_length, views, season, episode, title
        params = {
            "page": page,
            "dir": direction,
            "order": order,
        }
        #
        if tags:
            if isinstance(tags, list):
                params['tags'] = tags
            else:
                params['tags'] = [tags]
        #
        dn = WebResource.WebResource(
            self._addon,
            self.apiUrlSearch,
            pUseragent=self.userAgent
        )
        #
        return dn.retrieveAsString(postData=params)

    def loadTags(self):
        #
        fullurl = f"{self.apiUrlTags}"
        self.logger.debug('url {}', fullurl)
        #
        dn = WebResource.WebResource(self._addon, fullurl, pUseragent=self.userAgent)
        dataString = dn.retrieveAsString()
        # self.logger.debug('datastr {}', dataString)
        #
        return dataString


    def getM3U8UrlByEpisodeId(self, episodeid):
        #
        try:
            fullurl = f"{self.apiUrlVideoPlaylist}/{episodeid}"
            self.logger.debug('url {}', fullurl)
            #
            dn = WebResource.WebResource(self._addon, fullurl, pUseragent=self.userAgent)
            dataString = dn.retrieveAsString()
            # self.logger.debug('datastr {}', dataString)
            #
            data = json.loads(dataString)
            #self.logger.debug('datajson {}', data)
            #
            if data['data']['urls']['playlist']:
                return data['data']['urls']['playlist']
            else:
                self.logger.warn('No Playlist Url from API. Response: {}', data)
                return ""
        #
        except Exception as err:
            self.logger.error('getM3U8UrlByEpisodeId {}', err)
            self.kodiPG.close()
            raise
        #
        return ""

