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

import requests
from scraper.utils.browser import Firefox
from scraper.utils.resolve import Resolver
from scraper.utils.common import genIP

class Markiza(Resolver):
    def __init__(self):
        self.channels = {
            'markiza': 'https://media.cms.markiza.sk/embed/6EiuEYTfM1m?autoplay=1',
            'doma': 'https://media.cms.markiza.sk/embed/1EzNOAGdOjl?autoplay=1',
            'dajto': 'https://media.cms.markiza.sk/embed/HhDydkbM0h2?autoplay=1',
            'krimi': 'https://media.cms.markiza.sk/embed/5optAOIvjKG?autoplay=1'
        }

    def grab(self, channel):
        if channel not in self.channels: return 'Channel not found'
        firefox = Firefox()
        
        firefox.addHeader("Referer", 'https://videoarchiv.markiza.sk/')

        hlsurl = ""
        attempts = 0
        while attempts <= 10:
            firefox.addHeader("X-Forwarded-For", genIP("SK"))
            r = requests.get(self.channels[channel], headers=firefox.headers)
            if "processAdTagModifier" in r.text:
                hlsurl = r.text.split('processAdTagModifier({"tracks":{"HLS":[{"src":"')[1].split('","')[0].replace('\/','/')
                firefox.addHeader("Referer", self.channels[channel])
                return hlsurl, firefox.headers
            attempts += 1
        return "", {}
