import org.serviio.library.metadata.*
import org.serviio.library.online.*
import groovy.json.*

/**
 * SVTHD.tv (svtplay.se) content URL extractor plugin. 
 * Only 2 items SVT1 HD and SVT2 HD (-> hardcoded)  
 *
 *  
 * @author Stefan Andersson
 *
 */
class SVTHD extends WebResourceUrlExtractor
  {
    
    final VALID_RESOURCE_URL = '^https?://.*svthd.tv$'
        
    String getExtractorName()
    {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL resourceUrl)
    {
        return resourceUrl ==~ VALID_RESOURCE_URL
    }
    
    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve)
    {
       
        def items = []
                     
        items.add(new WebResourceItem(title : "SVT1 HD",
                                      additionalInfo : ['content' : "http://www.svtplay.se/kanaler/svt1",
                                                        'thumb' : "http://www.lyngsat-logo.com/hires/ss/svt_1_hd.png"]))
        items.add(new WebResourceItem(title : "SVT2 HD",
                                      additionalInfo : ['content' : "http://www.svtplay.se/kanaler/svt2",
                                                        'thumb' : "http://www.lyngsat-logo.com/hires/ss/svt_2_hd.png"]))        
                                    
        return new WebResourceContainer(title : "", items: items)
    }

    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality)
      {

        final param = "?output=json"
        final user_agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"
 
        def linkUrl = item.additionalInfo['content'] + param
        def thumbnailUrl = item.additionalInfo['thumb']
       
        def json = new JsonSlurper().parseText(openURL(new URL(linkUrl), user_agent))

        def url_ios = json.video.videoReferences.find() {it.playerType == "ios"}.url

        def master = openURL(new URL(url_ios), user_agent)

        def matcher = master =~ '(?s)EXT-X-STREAM-INF.*?BANDWIDTH=(\\d+?),.*?(https://.+?)(#|$)'

        def list = []
        for (int i = 0; i < matcher.size(); i++)
        {
            list << ['url': matcher[i][2], 'bitrate': matcher[i][1].toInteger()]
        }
        def contentUrl = list.sort{ it.bitrate }.reverse()[0].url
          
        return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: thumbnailUrl, live : true, expiresImmediately : true, cacheKey : linkUrl)
     }
}