"""Plugin for NHK World, NHK Japan's english TV channel."""

import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.stream import HDSStream

API_URL = "http://api.sh.nhk.fivecool.tv/api/cdn/?publicId=3bz2huey&playerId=7Dy"

_url_re = re.compile("http(s)?://(\w+\.)?nhk.or.jp/nhkworld")
_schema = validate.Schema({
    "live-streams": [{
        "streams": validate.all(
            [{
                "protocol": validate.text,
                "streamUrl": validate.text
            }],
            validate.filter(lambda s: s["protocol"] in ("http-flash", "http-hds"))
        )
    }]
})


class NHKWorld(Plugin):
    @classmethod
    def can_handle_url(cls, url):
        return _url_re.match(url)

    def _get_streams(self):
        res = http.get(API_URL)
        data = http.json(res, schema=_schema)

        streams = {}
        for livestreams in data["live-streams"]:
            for stream in livestreams["streams"]:
                url = stream["streamUrl"]
                for name, stream in HDSStream.parse_manifest(self.session, url).items():
                    if name.endswith("k"):
                        streams[name] = stream

        return streams


__plugin__ = NHKWorld

@@ -182,17 +182,17 @@
 import H
-D
+L
 SStream%0A
@@ -214,70 +214,52 @@
 p://
-api.sh.nhk.fivecool.tv/api/cdn/?publicId=3bz2huey&playerId=7Dy
+%7B%7D.nhk.or.jp/nhkworld/app/tv/hlslive_web.xml
 %22%0A%0A_
@@ -288,18 +288,24 @@
 ttp(
+?:
 s)?://(
+?:(
 %5Cw+
+)
 %5C.)?
@@ -355,284 +355,59 @@
 ema(
-%7B
 %0A    
-%22live-streams%22: %5B%7B%0A        %22streams%22: validate.all(%0A            %5B%7B%0A                %22protocol%22: validate.text,%0A                %22streamUrl%22: validate.text%0A            %7D%5D,%0A            validate.filter(lambda s: s%5B%22protocol%22%5D in (%22http-flash%22, %22http-hds%22))%0A        )%0A    %7D%5D%0A%7D
+    validate.xml_findtext(%22./main_url/wstrm%22)%0A
 )%0A%0A%0A
@@ -514,16 +514,28 @@
 tch(url)
+ is not None
 %0A%0A    de
@@ -568,279 +568,263 @@
     
-res = http.get(API_URL)%0A        data = http.json(res, schema=_sc
+# get the HLS xml from the same sub domain as t
 he
+ 
 ma
-)%0A%0A        streams = %7B%7D%0A        for livestreams in data%5B%22live-streams%22%5D:%0A            for stream in livestreams%5B%22streams%22%5D:%0A                url = stream%5B%22streamUrl%22%5D%0A                for name, stream in HD
+in url, defaulting to www%0A        sdomain = _url_re.match(self.url).group(1) or %22www%22%0A        res = http.get(API_URL.format(sdomain))%0A%0A        stream_url = http.xml(res, schema=_schema)%0A        return HL
 SStr
@@ -837,14 +837,22 @@
 rse_
-manife
+variant_playli
 st(s
@@ -868,135 +868,19 @@
 on, 
-url).items():%0A                    if name.endswith(%22k%22):%0A                        streams%5Bname%5D = stream%0A%0A        return streams
+stream_url)
 %0A%0A%0A_

update the plugin to use the new HLS streams