import logging
import re

from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.plugin.api.utils import itertags
from streamlink.stream.hls import HLSStream

log = logging.getLogger(__name__)


@pluginmatcher(re.compile(
    r'https?://vtvgo\.vn/xem-truc-tuyen-kenh-'
))
class VTVgo(Plugin):
    AJAX_URL = 'https://vtvgo.vn/ajax-get-stream'

    _params_re = re.compile(r'''var\s+(?P<key>(?:type_)?id|time|token)\s*=\s*["']?(?P<value>[^"']+)["']?;''')

    _schema_params = validate.Schema(
        validate.transform(lambda html: next(tag.text for tag in itertags(html, "script") if "setplayer(" in tag.text)),
        validate.transform(_params_re.findall),
        [
            ("id", int),
            ("type_id", str),
            ("time", str),
            ("token", str)
        ]
    )
    _schema_stream_url = validate.Schema(
        validate.parse_json(),
        {"stream_url": [validate.url()]},
        validate.get("stream_url"),
        validate.get(0)
    )

    def _get_streams(self):
        self.session.http.headers.update({
            'Origin': 'https://vtvgo.vn',
            'Referer': self.url,
            'X-Requested-With': 'XMLHttpRequest',
        })
        params = self.session.http.get(self.url, schema=self._schema_params)

        log.trace('{0!r}'.format(params))
        hls_url = self.session.http.post(self.AJAX_URL, data=dict(params), schema=self._schema_stream_url)

        return HLSStream.parse_variant_playlist(self.session, hls_url)


__plugin__ = VTVgo

@@ -118,57 +118,8 @@
 ate%0A
-from streamlink.plugin.api.utils import itertags%0A
 from
@@ -514,112 +514,173 @@
 ate.
-transform(lambda html: next(tag.text for tag in itertags(html, %22script%22) if %22setplayer(%22 in tag.text)),%0A
+parse_html(),%0A        validate.xml_xpath_string(%22.//script%5Bcontains(text(),'setplayer(')%5D%5B1%5D/text()%22),%0A        validate.any(None, validate.all(%0A            str,%0A    
     
@@ -735,10 +735,18 @@
     
-%5B%0A
+    %5B%0A    
     
@@ -778,16 +778,20 @@
         
+ 
+   
 (%22type_i
@@ -792,32 +792,36 @@
 type_id%22, str),%0A
+    
             (%22ti
@@ -843,16 +843,20 @@
         
+    
 (%22token%22
@@ -870,17 +870,32 @@
         
+  
-%5D
+  %5D%0A        ))
 %0A    )%0A 
@@ -1358,16 +1358,58 @@
 _params)
+%0A        if not params:%0A            return
 %0A%0A      
@@ -1424,30 +1424,21 @@
 ace(
-'%7B0!r%7D'.format(
+f%22%7B
 params
-)
+!r%7D%22
 )%0A  

remove itertags