import org.serviio.library.online.WebResourceUrlExtractor
import org.serviio.library.online.WebResourceContainer
import org.serviio.library.online.ContentURLContainer
import org.serviio.library.online.WebResourceItem
import org.serviio.library.online.PreferredQuality
import org.serviio.library.metadata.MediaFileType
/**
 * WebResource extractor Serviio plugin for conectate <br/>
 * <b>version</b> 1.0
 *
 * @author Hernan Bazan
 * @since JDK 1.6, Groovy 1.8.6
 */
class CONECTATE extends WebResourceUrlExtractor{
    ////////////////////////////////////////////[Constants]////////////////////////////////////////////
    final static VALID_WEB_RESOURCE_URL                     = '^(?:http?://)?conectate.*'
    final static DEFAULT_EPISODE_DOMAIN                     = "http://conectate.gov.ar"
    final static DEFAULT_VIDEO_DOMAIN                       = "http://repositoriovideo-streaming.educ.ar"
    final static USER_AGENT                                 = 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1'
    final static HREF_REGEX                                 = /(?s)<a href="(.*?)<\/a>/
    final static THUMBNAIL_REGEX                            = /(?s) id="tabVote">(.*)<img src="(.*?)" height="24"/
    final static VIDEO_REGEX                                = /(?s)'hd.file'\s:\s'(.*?)'/
    final static EPISODE_URL_PREFIX                         = "/educar-portal-video-web/module/detalleRecurso/DetalleRecurso.do";
    final static VIDEO_URL_PREFIX                           = "/repositorio/Video/ver";
    /////////////////////////////////////////////[Methods]/////////////////////////////////////////////
    @Override
    protected WebResourceContainer extractItems(URL url, int i) {
        def videoURLsSet = retrieveURLs(url);
        return new WebResourceContainer(title: url.toString(), items: retrieveURLs(url))
    }
    List<WebResourceItem> retrieveURLs(URL url) {
        Set<String> pages = new HashSet<String>();
        List<WebResourceItem> items = []
        String pageSource = openURL(url, USER_AGENT)
        String candidate;
        (pageSource=~HREF_REGEX).each {
            candidate = (it-null)[-1];
            if(candidate.startsWith(EPISODE_URL_PREFIX)){
                if(!pages.contains(candidate)){
                    String uri = ((candidate=~/(?<u>.*)">(?<t>.*)/))[0][1].toString().trim()
                    String title = ((candidate=~/(?<u>.*)">(?<t>.*)/))[0][2].toString().trim()
                    if(title){
                        pages.add(uri);
                        Map<String,String> additionalInfo = new HashMap<String, String>();
                        additionalInfo.put("videoURL",DEFAULT_EPISODE_DOMAIN + uri)
                        items << new WebResourceItem(title: title, additionalInfo: additionalInfo)
                    }
                }
            }
        }
        return items;
    }
    @Override
    protected ContentURLContainer extractUrl(WebResourceItem webResourceItem, PreferredQuality preferredQuality) {
        URL videoPageURL = new URL(webResourceItem.getAdditionalInfo().get("videoURL"))
        log(String.format("[%s] Staring video URL extraction for %s",getExtractorName(),videoPageURL))
        ContentURLContainer contentURLContainer = new ContentURLContainer();
        try{
            fillURLContainer(videoPageURL,contentURLContainer)
            return contentURLContainer
        }catch (IndexOutOfBoundsException e){
            log.error(String.format("%s , Failed to create resource item for URL: %s",getExtractorName(), it), log.isDebugEnabled()? e:null)
        }
        return null
    }
    void fillURLContainer (URL url,ContentURLContainer contentURLContainer) {
        String pageSource = openURL(url, USER_AGENT)
        //contentURLContainer.setThumbnailUrl(((pageSource=~THUMBNAIL_REGEX)[0]-null)[-1].toString().trim())
        contentURLContainer.setContentUrl(new URLDecoder().decode(((pageSource=~VIDEO_REGEX)[0]-null)[-1].toString().trim()))
    }
    @Override
    boolean extractorMatches(URL url) {
        return url ==~ VALID_WEB_RESOURCE_URL
    }

    @Override
    String getExtractorName() {
        return getClass().getName()
    }
    static void main(args) {
        def TestUrl = new URL("http://conectate.gov.ar/educar-portal-video-web/module/detalleRecurso/DetalleRecurso.do?modulo=masVotados&idRecurso=50585")
        CONECTATE extractor = new CONECTATE()
        WebResourceContainer container = extractor.extractItems(TestUrl, -1);
        println "PluginName               : " + extractor.getExtractorName();
        println "TestMatch                : " + extractor.extractorMatches(TestUrl);
        container.getItems().each {
            println "URL                  : " + extractor.extractUrl(it, PreferredQuality.HIGH)
        }
    }
}