import org.serviio.library.metadata.*
import org.serviio.library.online.*

/**
 * PBS.org content URL extractor plugin. 
 *  
 * @author Dylan Freadhoff
 *
 */
class PBSURLExtractor extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://video.pbs.org/.*$'
    
    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default.toString()
        String videoInfoUrl = linkUrl.replaceAll(/\/video\//, "/videoPlayerInfo/")

        def packageNode = new XmlParser().parse( videoInfoUrl )
        def contentUrl = packageNode.videoInfo[0].episode_website[0].text()
        def thumbnailUrl = packageNode.videoInfo[0].thumbnailURL[0].text()

        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)
    }
    
    static void main(args) {
        // this is just to test
        PBSURLExtractor extractor = new PBSURLExtractor()
        
        assert extractor.extractorMatches( new URL("http://video.pbs.org/video/2169255600/") )
        assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") )
        
        Map links = ['default': new URL('http://video.pbs.org/video/2169255600/')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
    }
}