import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.ccil.cowan.tagsoup.*
/**
 * LiveFreeCamX.com content URL extractor plugin. 
 * 
 *
 *  
 * @author Pornoman
 *
 */
class LiveFreeCamX extends WebResourceUrlExtractor {

    final VALID_RESOURCE_URL = '^https?://.*livefreecamx\\..*$'
        
    String getExtractorName() {
        return getClass().getName()
    }
    
    boolean extractorMatches(URL resourceUrl) {
        return resourceUrl ==~ VALID_RESOURCE_URL
    }
    
    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {

        def conn = resourceUrl.openConnection()
        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")

        def root = new XmlSlurper(new Parser()).parseText(conn.getInputStream().getText())

        def node = root.depthFirst().find {it.@class == "list"}

        def items = []

	node.children().eachWithIndex() {

               obj, i ->
               if (maxItemsToRetrieve == -1 || i <= maxItemsToRetrieve - 1 ) {   

                 def image = obj.a.img.@src.text()                
                 def href = obj.div.div.a.@href.text()
                 def title = obj.div.div.a.text()

                 items.add(new WebResourceItem(title : title, additionalInfo : ['content' : href, 'thumb' : image]))
   
                 log("image: $image")
                 log("href: $href")
                 log("title: $title")

               }
        }
                      
        return new WebResourceContainer(title : "", items: items)

    }

    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {

        def linkUrl = "http://www.livefreecamx.com" + item.additionalInfo['content']
        def thumbnailUrl = item.additionalInfo['thumb']

        def html = openURL(new URL(linkUrl), "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")

        def contentUrl = html.find(/http.*m3u8/)
          
        return new ContentURLContainer(contentUrl: contentUrl, thumbnailUrl: thumbnailUrl)

    }

 }