# -*- coding: utf-8 -*-
# Author: Parrot Developers
# License: MPL 2.0 https://www.mozilla.org/en-US/MPL/2.0/

import time
import requests
from ..utils.browser import Firefox
from ..utils.resolve import Resolver
from ..utils.localstorage import readFromStorage, writeToStorage

class Rebit(Resolver):
    def __init__(self):
        self.server = "https://bbxnet.api.iptv.rebit.sk"
        self.firefox = Firefox()
        self.firefox.addHeader("Referer", "https://rebit.tv/")

    def __login(self, username="qdr61374@xcoxc.com", password="14066176"):
        """
        args:
            username (str): Username to log in with
            password (str): Password to log in with

        returns:
            data (dict): Contains "access_token", "user_id", "refresh_token", "expire_in", "client"
        """

        data = {
            "username": username,
            "password": password
        }

        resp = requests.post(f"{self.server}/auth/auth", headers=self.firefox.headers, data=data).json()['data']
        
        # Get client
        resp['client'] = self.__getClient(resp['access_token'])

        return resp


    def __getClient(self, access_token):
        """
        args:
            access_token (str): Access Token

        returns:
            data (dict): Dict contains data about client
        """

        # I hope it doesn't change
        return {
            "id": "56ee6dc2-7fbe-49b4-99d0-c68a6983abfe",
            "fingerprint": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0",
            "heartbeat_at": int(time.time()),
            "last_channel_at": 1683740224,
            "last_channel_id": "4aeec652-c05e-4e12-aded-1d6d8bc69e8f",
            "last_channel_type": "live",
            "playlist_id": None,
            "title": "Firefox 112; Windows 10",
            "tv_archive_continued": "ask",
            "type": "computer",
            "user_id": "8d243fdf-833e-4a8d-b38a-fe02e7cd92f4",
            "created_at": 1681121663,
            "updated_at": int(time.time()),
        }

        headers = self.firefox.headers.copy()
        headers["Authorization"] = f"Bearer {access_token}"

        data = {
            "title":
            f"Firefox {self.firefox.version}; Windows 10",
            "childLockCode":"0000",
            "type":"computer"
        }
        resp = requests.post(f"{self.server}/television/client", headers=headers, data=data).json()
        if 'data' in resp:
            data = resp['data']
            del data['last_login_ip']
            del data['primary_phone']
            return data
        raise Exception(resp['message'])      


    def __refreshToken(self, refresh_token):
        """
        args:
            refresh_token (str): Refresh token is included in __login()
        """

        # To not edit global headers we need to create copy
        headers = self.firefox.headers.copy()
        headers["Authorization"] = f"Bearer {refresh_token}"

        resp = requests.post(f"{self.server}/auth/auth", headers=headers).json()
        if 'data' in resp: return resp['data']
        raise Exception(resp['message'])     


    def __getChannelByNumber(self, number):
        """
        args:
            number (str / int): Number of channel
        """

        resp = requests.get(f"{self.server}/television/channels", headers=self.firefox.headers).json()['data']

        for item in resp:
            if item["channel"] == int(number):
                return item
        return {}

    def grab(self, channel):
        data = readFromStorage("RebitData", ret={}, p=self.parent.data_file)
        if "user" in data.get("client", {}):
            data = {}

        if data == {}:
            if self.username and self.password: data = self.__login(username=self.username, password=self.password)
            else: data = self.__login()
        else:
            data.update(self.__refreshToken(data['refresh_token']))
        
        writeToStorage("RebitData", data, p=self.parent.data_file)

        # Add all headers required for api requests
        self.firefox.addHeader("Authorization", "Bearer " + data['access_token'])
        self.firefox.addHeader("X-Television-Client-ID", data['client']['id'])

        channel = self.__getChannelByNumber(channel)
        resp = requests.get(f"{self.server}/television/channels/{channel['id']}/play", headers=self.firefox.headers).json()['data']

        if 'link' in resp:
            self.firefox.removeHeaders(["Authorization", "X-Television-Client-ID"])
            return resp['link'], self.firefox.headers
        return "", {}