# -*- 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://api.gronkh.tv/v1/search'; # Options: ?first=24&direction=desc&sort=date
        self.apiUrlVideoPlaylist = 'https://api.gronkh.tv/v1/video/playlist' # Options: ?episode=<episodeid>
        self.apiUrlTags = 'https://api.gronkh.tv/v1/tags/all'
        #
        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.loadSearch(
                first = self.itemsPerPageNew,
                direction = "desc",
                sort = "date"
            ))
            # self.logger.debug('datajson {}', data)
            #
            results = pyUtils.extractJsonValue(data, 'results')
            if results:
                videos = pyUtils.extractJsonValue(results, 'videos')
                if videos:
                    for video in videos:
                        # self.logger.debug('video: {}', video)
                        streamliste.append(video)
                else:
                    self.logger.error('Could not find key "videos" in JSON. Data: ', results)
            else:
                self.logger.error('Could not find key "results" in JSON. Data: ', data)
        #
        except Exception as err:
            self.logger.error('getNewStreams {}', err)
            self.kodiPG.close()
            raise
        #
        self.kodiPG.close()
        return streamliste

    def getMostViewedStreams(self):
        self.logger.debug('getMostViewedStreams')
        streamliste = []
        self.kodiPG.create(30010)
        try:
            data = json.loads(self.loadSearch(
                first = self.itemsPerPageMost,
                direction = "desc",
                sort = "views"
            ))
            # self.logger.debug('datajson {}', data)
            #
            results = pyUtils.extractJsonValue(data, 'results')
            if results:
                videos = pyUtils.extractJsonValue(results, 'videos')
                if videos:
                    for video in videos:
                        # self.logger.debug('video: {}', video)
                        streamliste.append(video)
                else:
                    self.logger.error('Could not find key "videos" in JSON. Data: ', results)
            else:
                self.logger.error('Could not find key "results" in JSON. Data: ', data)
        #
        except Exception as err:
            self.logger.error('getMostViewedStreams {}', 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(
                first = 24,
                direction = "desc",
                sort = "date",
                tags=tagid
            ))
            # self.logger.debug('datajson {}', data)
            #
            results = pyUtils.extractJsonValue(data, 'results')
            if results:
                videos = pyUtils.extractJsonValue(results, 'videos')
                if videos:
                    for video in videos:
                        # self.logger.debug('video: {}', video)
                        streamliste.append(video)
                else:
                    self.logger.error('Could not find key "videos" in JSON. Data: ', results)
            else:
                self.logger.error('Could not find key "results" 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
        #
        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
        offset = ((page - 1) * self.itemsPerPage)
        self.logger.debug('getStreamsPaginated - Loading {} with offset {}', self.itemsPerPage, offset)
        lastepisode = 0
        try:
            data = json.loads(self.loadSearch(
                first = self.itemsPerPage,
                direction = "desc",
                sort = "date",
                offset = offset
            ))
            # self.logger.debug('datajson {}', data)
            #
            results = pyUtils.extractJsonValue(data, 'results')
            if results:
                videos = pyUtils.extractJsonValue(results, 'videos')
                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 "videos" in JSON. Data: ', results)
            else:
                self.logger.error('Could not find key "results" in JSON. Data: ', data)
        #
        except Exception as err:
            self.logger.error('getStreamsPaginated {}', err)
            self.kodiPG.close()
            raise

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


    def loadSearch(self, first = 24, direction = "desc", sort = "date", tags = None, offset = 0):
        # Possible directions: asc, desc
        # Possible sort: date, views
        params = {
            "first": first,
            "direction": direction,
            "sort": sort,
        }
        #
        if tags:
            if isinstance(tags, list):
                params['tags'] = ",".join(str(t) for t in tags)
            else:
                params['tags'] = tags
        #
        if offset > 0:
            params['offset'] = offset
        #
        filtered_params = {k: v for k, v in params.items() if v is not None and v != ""}
        query_string = urlencode(filtered_params)
        #
        fullurl = f"{self.apiUrlSearch}?{query_string}"
        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 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}?episode={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['playlist_url']:
                return data['playlist_url']
            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 ""

