import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.serviio.util.*
import groovy.util.XmlParser
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*
import java.util.regex.PatternSyntaxException
import java.util.regex.Pattern
import java.util.regex.Matcher
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

/**
 * WebResource plugin for Team Coco website (http://www.teamcoco.com/)
 * @author insane822
 * Version 1.1.3
 *
 * Currently Supports:
 * http://teamcoco.com/video/category/full-episodes/
 * http://teamcoco.com/video/category/live-coco-cam/
 * http://teamcoco.com/video/category/monologue/
 * http://teamcoco.com/video/category/music-and-bands/
 * http://teamcoco.com/video/category/stand-up/
 * http://teamcoco.com/video/category/web-exclusives/
 * http://teamcoco.com/video/category/comedy-sketches/
 * http://teamcoco.com/video/category/celebrity-interviews/
 * http://teamcoco.com/video/category/behind-the-scenes/
 */

class TeamCoco extends WebResourceUrlExtractor {

    // Feed URL regex
    final VALID_FEED_URL = '^http://teamcoco.com/video/category/.*'

    // Plug-in name
    String getExtractorName() {
        return 'TeamCoco'
    }

    // Valid URL
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }

    String user_agent = "Mozilla/5.0"

    // Resource Container
    WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
        List<WebResourceItem> items = []
        List episodes = []

        // Get all current episodes
        def m
        def html = openURL(resourceUrl, user_agent)
        //print html

        // Grab the unordered list for the matching category
        def video_category = html =~ /(?s)<ul.*data-slug=\"(full-episodes|music-and-bands|live-coco-cam|monologue|stand-up|web-exclusives|comedy-sketches|celebrity-interviews|behind-the-scenes)\">\r\n(.*)/


        // Grab the list of video ids from each list item
        m = video_category[0][2] =~ "<li class=\".*\" data-id=\"(\\d{5})\""

        // Loop through each list items and create a list of the episode xml data URLs
        for (episode in m) {
            print episode
            def x = "http://teamcoco.com/cvp/2.0/${episode[1]}.xml"
            episodes << x
        }


        for (String episode in episodes) {
            def sd,hd
            def Boolean rtmp
            def stream_data_xml = new XmlParser().parseText(openURL(new URL(episode), "derp"))
            String title = stream_data_xml.headline.text()
            String date = stream_data_xml.dateCreated.text()
            String thumbnail = stream_data_xml.images.image.findAll{it.'@height' == "360"}[0].text()
            String video_id = stream_data_xml.'@id'

            def rtmp_hd = stream_data_xml.files.file.findAll{it.'@size' == "1280x720"}[0]
            def rtmp_sd = stream_data_xml.files.file.findAll{it.'@size' == "640x360"}[0]
            def http_hd = stream_data_xml.files.file.findAll{it.'@type'.toString().toLowerCase() == "high"}[0]
            def http_sd = stream_data_xml.files.file.findAll{it.'@type'.toString().toLowerCase() == "standard"}[0]

            if (rtmp_hd) {
                hd = rtmp_hd.text()
                rtmp = true
            } else {
                hd = http_hd.text()
            }

            if (rtmp_sd) {
                sd = rtmp_sd.text()
                rtmp = true
            } else {
                sd = http_sd.text()
            }

            items << new WebResourceItem(title: title, releaseDate: new Date().parse('yyyy-MM-dd', date), additionalInfo: [hd: hd, sd: sd, video_id: video_id, rtmp: rtmp, thumbnailUrl: thumbnail])

        }



        return new WebResourceContainer(title: "Team Coco", items: items)

    }



    // Content URL
    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {

        //Setup rtmp_url
        def String stream_url
        def String contentUrl

        // Check requested quality and return appropriate stream
        if(requestedQuality == PreferredQuality.LOW) {
            stream_url = item.additionalInfo.sd
        }  else {
            stream_url = item.additionalInfo.hd
        }
        if (item.additionalInfo.rtmp) {
            contentUrl = getTokenUrl(stream_url, item.additionalInfo.video_id)
        } else {
            contentUrl = stream_url
        }

        String cacheKey = contentUrl

        return new ContentURLContainer(contentUrl: contentUrl, cacheKey: cacheKey, expiresImmediately: true, thumbnailUrl: item.additionalInfo.thumbnailUrl)
    }


    def getTokenUrl(stream_url, video_id) {
        def path_match = stream_url =~ /flash.*(?=.mp4)/
        String auth_string = openURL(new URL("http://www.tbs.com/processors/cvp/token.jsp?aifp=v001&authTokenType=d&window=28800&path=${path_match[0]}&videoId=${video_id}&profile=tbs"), user_agent)
        def token_match = auth_string =~ /<token>(.*)<\/token>/
        String contentUrl = "rtmpe://cp97384.edgefcs.net:1935/ondemand app=ondemand?${token_match[0][1]} playpath=${stream_url}"
        return contentUrl
    }

    // This is just to test, not actual code used for the plugin
    static void main(args) {

        TeamCoco extractor = new TeamCoco()

        String series_url = "http://teamcoco.com/video/category/full-episodes/"
        WebResourceContainer container = extractor.extractItems( new URL(series_url), -1)
        //print container
        container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.HIGH)
            println result
        }
        println container

    }
}

