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

import requests
import re
import json
from bs4 import BeautifulSoup
from scraper.utils.browser import Firefox
from scraper.utils.resolve import Resolver
from scraper.utils.errors import Error

class JOJ(Resolver):
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update(Firefox().headers)
        self.session.headers.update({
            "Referer": "https://www.joj.sk/"
        })

        self.static_links = {
            "1-joj": "https://live.cdn.joj.sk/live/andromeda/joj-1080.m3u8",
            "16-joj24": "https://live.cdn.joj.sk/live/andromeda/joj_news-1080.m3u8",
            "2-plus": "https://live.cdn.joj.sk/live/andromeda/plus-1080.m3u8",
            "x-family": "https://live.cdn.joj.sk/live/andromeda/family-1080.m3u8",
            "3-jojkrimi": "https://live.cdn.joj.sk/live/andromeda/wau-1080.m3u8",
            "5-jojko": "https://live.cdn.joj.sk/live/andromeda/jojko-1080.m3u8",
            "6-cinema": "https://live.cdn.joj.sk/live/andromeda/cinema-1080.m3u8",
            "10-cs%20film": "https://live.cdn.joj.sk/live/andromeda/cs_film-1080.m3u8",
            "11-cs%20history": "https://live.cdn.joj.sk/live/andromeda/cs_history-1080.m3u8",
            "12-cs%20mystery": "https://live.cdn.joj.sk/live/andromeda/cs_mystery-1080.m3u8",
            "15-jojsport": "https://live.cdn.joj.sk/live/andromeda/joj_sport-1080.m3u8",
            "180-jojsport2": "https://live.cdn.joj.sk/live/andromeda/joj_sport2-1080.m3u8",
            #"114-jojsvet": "",
        }

    def get_dynamic_id(self, channel_id):
        html = self.session.get(f"https://www.joj.sk/live/1-joj").text
        
        soup = BeautifulSoup(html, 'html.parser')
        player_element = soup.find("joj-live-player")
        
        json_data = json.loads(player_element.attrs[':data']) # NOTE: This can be cached
        
        for channel in json_data['channels']:
            if channel['live_url'] != f"https://www.joj.sk/live/{channel_id}":
                continue
            return channel['livestream_id']
        return None
    
    def grab(self, channel):
        if channel in self.static_links:
            return self.static_links[channel], \
                    {"User-Agent": self.session.headers["User-Agent"], "Referer": "https://www.joj.sk/"}

        try:
            dynamic_id = self.get_dynamic_id(channel)
            if not dynamic_id:
                return Error().channel_not_found()
        except:
            return Error().channel_not_found()

        json_data = {
            'data': {
                'id': dynamic_id,
                'documentType': 'tvChannel',
                'sourceHistory': [],
                'capabilities': [
                    {
                        'codec': 'h264',
                        'protocol': 'hls',
                        'encryption': 'none',
                    },
                ],
            },
        }

        response = self.session.post(
            'https://europe-west3-tivio-production.cloudfunctions.net/getSourceUrl',
            json=json_data,
        )
        if response.status_code != 200:
            return Error().channel_not_found()

        return response.json()['result']['url'], self.session.headers