import java.net.URL

import org.serviio.library.metadata.*
import org.serviio.library.online.*
import groovy.json.*
import groovy.xml.*

/**
 * Tou.TV plugin pour Serviio. 
 * 
 * @author Mathieu Fortin
 *
 * Library -> Online Sources -> Add
 * Source type : Web Resource
 * Source url  : http://tou.tv/19-2
 * Display name: 19-2
 *
 */
 
class TouTV extends WebResourceUrlExtractor {
    final Integer VERSION = 1
    //Regex ... http://tou.tv/<Emission>, teste avec 19-2 et enquete
    final String VALID_FEED_URL   = '^http://(?:www.)?tou.tv/([a-zA-Z0-9_-]+)$'
    // Adresse des API
    final String API_GETSHOWS_URL = "http://api.tou.tv/v1/toutvapiservice.svc/json/GetPageRepertoire"
    final String API_GETSHOW_URL  = "http://api.tou.tv/v1/toutvapiservice.svc/json/GetPageEmission?emissionId="
    final String API_GETVIDEO_URL = "http://api.radio-canada.ca/validationMedia/v1/Validation.html?appCode=thePlatform&deviceType=Android&output=json&connectionType=wifi&idMedia="
    
    int getVersion() {
        return VERSION
    }

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }

    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {    
        // On va chercher le nom de l'émission, et on extrait le json du repertoire
        def nomEmission = (resourceUrl =~ VALID_FEED_URL)[0][1]
        def jsonText = new URL(API_GETSHOWS_URL).text
        def json = new JsonSlurper().parseText(jsonText)

        def emissions = json.d.Emissions
       
        def items = []
        def episodeID
        def thumbEmission
        
        // Si nous avons des emissions dans le repertoire
        if(emissions.size() > 0) {
            emissions.each {
                // Quand le titre match ce que nous recherchons
                if(it.Url == nomEmission){
                    episodeID = it.Id
                    thumbEmission = it.ImagePromoNormalK
                }
            }
        }

        //On va chercher le json de cette serie
        def otherjsonText = new URL(API_GETSHOW_URL + episodeID).text
        def otherjson = new JsonSlurper().parseText(otherjsonText)
        
        //Seulement la partie Episodes de la reponse nous interesse
        def emission = otherjson.d.Episodes
        
        if(emission.size() > 0)
            emission.each {
                // Le titre, par exemple 19-2 S01E01
                def title = nomEmission + " " + it.SeasonAndEpisode
                // La date de diffusion
                def episodeDate = it.AirDateFormated
                def newdate = new Date().parse("yyyyMd", episodeDate)
                //Le PID de l'episode
                def pid = it.PID

                def jsonUrl = new URL( API_GETVIDEO_URL + pid).text
                def url = new JsonSlurper().parseText(jsonUrl)
                
                def mediaUrl = (url.url =~ '(.*?)\\?.*')[0][1]

                //Nos items pour le conteneur, avec le titre, adresse du flux et date de diffusion
                //swfUrl=http://static.tou.tv/lib/ThePlatform/4.1.2/swf/flvPlayer.swf
                items += new WebResourceItem(title: title, releaseDate: newdate, additionalInfo: [ 
                    expiresImmediately: true,
                    cacheKey: nomEmission + it.SeasonAndEpisode,
                    episodeUrlLd: mediaUrl.replaceAll('_800','_500'),
                    episodeUrlMd: mediaUrl,
                    episodeUrlHd: mediaUrl.replaceAll('_800','_3000'),
                    thumbnail: it.ImageThumbNormalF ]
                )
            }

        return new WebResourceContainer(title: nomEmission, thumbnailUrl: thumbEmission, items: items)
    }    

    ContentURLContainer extractUrl(WebResourceItem arg0, PreferredQuality requestedQuality) {
        def c = new ContentURLContainer()
        if(arg0 != null) {
            c.setExpiresImmediately(arg0.additionalInfo.expiresImmediately)
            c.setCacheKey(arg0.additionalInfo.cacheKey)
            if(requestedQuality == PreferredQuality.HIGH) {
                c.setContentUrl(arg0.additionalInfo.episodeUrlHd)
            } else if(arg1 == PreferredQuality.MEDIUM) {
                c.setContentUrl(arg0.additionalInfo.episodeUrlMd)
            } else {
                c.setContentUrl(arg0.additionalInfo.episodeUrlLd)
            }
            c.setLive(false)
            c.setThumbnailUrl(arg0.additionalInfo.thumbnail)
        }

        return c
    }
    
    static void main(args) {
        TouTV toutv = new TouTV()
        
        def items = toutv.extractItems(new URL("http://www.tou.tv/19-2"), 1)
        ContentURLContainer result = toutv.extractUrl(items.getItems()[0], PreferredQuality.HIGH)
        println result
    }
}