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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * WimpCom content URL extractor plugin v1.0 
 *  
 * @author Appie Mulder
 *
 */
class WimpCom extends FeedItemUrlExtractor {
    
    final VALID_FEED_URL = '^http(s)*://www.wimp.com/rss.*$'

    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL
    }
    
    ContentURLContainer extractUrl(Map links, PreferredQuality requestedQuality) {
        def linkUrl = links.default
        //println "linkUrl: $linkUrl"

        def url1 = new URL("$linkUrl")
        URLConnection conn1 = url1.openConnection()
        conn1.connect()

        String metahtml = conn1.getContent().getText()
        //println "metahtml: $metahtml"

        def flvUrl = find("http://rom.wimp.com/videos(.*?)\"", metahtml);
        flvUrl = 'http://rom.wimp.com/videos' + flvUrl
        //println "flvUrl: $flvUrl"

        return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: flvUrl)
    }
    
    static void main(args) {
        // this is just to test
        WimpCom extractor = new WimpCom()

        assert extractor.extractorMatches( new URL("http://www.wimp.com/rss") ) 
        assert !extractor.extractorMatches( new URL("http://google.com/feeds/api/standardfeeds/top_rated?time=today") ) 

        Map links = ['default': new URL('http://www.wimp.com/dogpuppeteer/')] 
        ContentURLContainer result = extractor.extractUrl(links, PreferredQuality.MEDIUM)
        println "Result: $result"
    }
    
    private static String find(String regex, String XMLcontent) {
        Matcher m = Pattern.compile(regex, Pattern.DOTALL).matcher(XMLcontent);
        if (!m.find()) {
            return null;
        }
        return m.group(1).trim();
    }
    
}