import groovy.json.JsonSlurper
import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.slf4j.*
import org.serviio.util.*
import groovy.xml.XmlUtil


/**
 * VBoxextractor is an URL extractor plugin that extracts VBox's channel list
 *
 *
 */

class VBoxChannels extends WebResourceUrlExtractor {
    // URL for the page with the list of channels
    final static CHANNELSURL = '/cgi-bin/HttpControl/HttpControlApp?OPTION=1&Method=GetXmltvChannelsList&FromChIndex=FirstChannel&ToChIndex=LastChannel'
    
    final String extractorName = getClass().name
  
    final String containerTitle = 'VBoxLiveTV'

    // Path for optinal thumbnails overwritting the ones comming from the VBOX
    final String pluginDir = new File(getClass().protectionDomain.codeSource.location.path.replaceAll('%20', ' ')).parent
    final String thumbnailDir = pluginDir + '/' + extractorName + '/thumbnails/'

    //File f = new File("/Users/manuel/tmp.txt");
    
    @Override
    boolean extractorMatches(URL feedUrl) {
        def tmp = feedUrl.toString()
        return (tmp.startsWith('http://'+extractorName+'.'))
    }

    @Override
    WebResourceContainer extractItems(URL resourceUrl, int maxItemsToRetrieve) {
        // the URL should be http://extractorName.IP http:// plus the . are the 7 characters
        final url = resourceUrl.toString().substring(extractorName.length()+8,resourceUrl.toString().length())

        final items = []

        // parse the xml file from the VBox
        String xmlfile = openURL(new URL('http://'+url + CHANNELSURL), null)
        xmlfile = xmlfile.substring(xmlfile.indexOf('<tv'),xmlfile.length())
        def rootNode = (new XmlParser(false,false)).parseText(xmlfile)

        // add the channels
        def channelsFound = 0
        rootNode.channel.each
        {
           def cUrl = it.url[0].'@src'
           def tUrl = it.icon[0].'@src'
           def name = it.'display-name'[0].text()
           // If the VBoxChannels directory exist and it has an icon with the name of the channel use it
           tUrl = getThumbnail(name,tUrl)
           channelsFound ++
 
           name = "" + String.format("%02d", channelsFound) + " " + name;

           // Add the channel to the list of channels
           items.add(new WebResourceItem(title: name ,  additionalInfo: ['contentUrl':cUrl,'thumbnailUrl':tUrl]))
           if(channelsFound > maxItemsToRetrieve )
           {
              //items.sort();
              return new WebResourceContainer(
                  title: containerTitle ,
                  thumbnailUrl: 'file://' + thumbnailDir + 'VBox.jpg',
                  items: items
              )
            }
	}

        //items.sort();
        return new WebResourceContainer(
            title: 'VBox',
            items: items
        )
    }

    @Override
    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
        final info = item.additionalInfo
        return new ContentURLContainer(
            fileType: MediaFileType.VIDEO,
            contentUrl: info['contentUrl'],
            thumbnailUrl: info['thumbnailUrl'],
            live: true
        )
    }


    @Override
    int getVersion()
    {
       return 3
    }

    @Override
    int getExtractItemsTimeOut()
    {
       return 65
    }

    @Override
    String getExtractoName()
    {
       return 'VBox'
    }

    /**
    *  It searches for a an file with extension png first and jpg then with the name of the channel in a directory 
    *  with the same name as the class/thumbnails. It puts the name in lowee case and it removes spaces and 
    *  forward and back slashes. It the file is not found it returns the given url.
    *  @param name String Name of the channel
    *  @param url  String Name of the default url in case the file is not found
    *  @return The found file name or the default url if not found
    */
    String getThumbnail(String name, String url)
    {
      name = thumbnailDir + name.toLowerCase().replaceAll("\\s","").replaceAll("\\\\","").replaceAll("/","")
      if((new File(name+'.png')).exists())return 'file://' +  name+'.png'
      if((new File(name+'.jpg')).exists())return 'file://' +  name+'.jpg'
      return url
    }
}
