import groovy.util.XmlParser

import org.serviio.library.metadata.*
import org.serviio.library.online.*

import groovy.util.XmlSlurper
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.text.ParsePosition
/********************************************************************
 * Escapist.com plugin for Serviio 
 * Made with assistance from examples on Serviio.org
 *
 * @author Mike_Metro
 * Version:  3.0
 * Sample URLs: http://www.escapistmagazine.com/rss/videos/list/1.xml
 * more at:  http://www.escapistmagazine.com/rss/  
 ********************************************************************/

class Escapist extends WebResourceUrlExtractor {
    
    final VALID_FEED_URL = '^(?:http://)?(www\\.)?escapistmagazine\\.com/rss/videos/list/.*$'
    
    String getExtractorName() {
        return 'Escapist'
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
       
    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {
        List<WebResourceItem> items = []
        def itemsAdded = 0
        def channelXML = new XmlSlurper().parse(resourceUrl.toString()).channel
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
        
        
        channelXML.item.find { 
            items << new WebResourceItem(title: it.title.text(), releaseDate: dateFormat.parse(it.pubDate.text(), new ParsePosition(0)) , additionalInfo: ['link':it.link.text()])
            itemsAdded++
            if (maxItemsToRetrieve != -1 && itemsAdded >= maxItemsToRetrieve) return true
            return false
        }

        return new WebResourceContainer(title: channelXML.title.text() , thumbnailUrl: channelXML.image.url.text() , items: items)
    }

    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
			
        def pageContent = new URL(item.additionalInfo.link).getText()
    
        def matcher = pageContent =~ '<param name="flashvars" value="config\\=(.*?)"\\/>'            
	//added user agent	
        def jsContent = new URL(URLDecoder.decode(matcher[0][1],'UTF-8')).getText(requestProperties:['User-agent':'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'])
	
    //json didn't work.  Just parsed in with regexp
        def vidMatcher = jsContent =~ /\{'url':'(.*?)'.*?'Video Splash'\}.*?\{'url':'(.*?)'.*?'LR_VIDEO_ID':'(.*?)'.*?\}/

        def contentUrl = vidMatcher[0][2]
        def thumbnailUrl = vidMatcher[0][1]
        def videoId  = vidMatcher[0][3]  
        def cacheKey = "Escapist_${videoId}_${requestedQuality}"
        return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: thumbnailUrl, expiresImmediately: true, cacheKey : cacheKey)
    }

    
    static void main(args) {
        // Test
        Escapist extractor = new  Escapist()
        
        WebResourceContainer container = extractor.extractItems( new URL("http://www.escapistmagazine.com/rss/videos/list/1.xml"), 5)

        container.getItems().each {
            ContentURLContainer result = extractor.extractUrl(it, PreferredQuality.MEDIUM)
            println result 
        }   
    }
}