import org.serviio.library.metadata.*
import org.serviio.library.online.*
import org.apache.commons.lang.RandomStringUtils
import javax.script.*


/**
 * WebResource extractor plugin for watching series from tubeplus.me
 *
 * @author amnarciso
 * @version 1
 */
class TubePlus extends WebResourceUrlExtractor {

    final int VERSION = 1
    final VALID_FEED_URL = '^http://.*tubeplus.me.*$'
    final USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36'
    final BASE_URL = 'http://www.tubeplus.me'
    final LOGO = 'http://www.playonscripts.com/images/icons/0MycZgC9fon2.png'

    String getExtractorName() {
        return getClass().getName()
    }

    int getVersion() {
        return VERSION
    }

    boolean extractorMatches(URL feedUrl) {
        return feedUrl ==~ VALID_FEED_URL;
    }
    
    def getStream(String vid, String vtitle, String vhost) {
        URL resourceUrl
        String itemUrl
        String itemLogo
        Boolean found = false

        //Try to extract stream from [gorillavid.in]
        if (vhost == 'gorillavid.in'){
            String movieUrl = 'http://gorillavid.in/embed-' + vid + '-650x400.html'

            resourceUrl = new URL(movieUrl)
            String movieUrlContent = resourceUrl.getText()

            itemUrl = movieUrlContent.find('file: "[^"]+"')
            itemLogo = movieUrlContent.find('image: "[^"]+"')
            if (itemUrl){
                itemUrl = itemUrl[7..-2]
                itemLogo = itemLogo[8..-2]
                found = true
            }
        }

        //Try to extract stream from [vidbull.com]
        if (vhost == 'vidbull.com'){
            String movieUrl = 'http://vidbull.com/embed-' + vid + '-650x328.html'
   
            resourceUrl = new URL(movieUrl)
            String movieUrlContent = resourceUrl.getText()
                
            movieUrlContent = movieUrlContent.findAll(/eval\(.*\)/)[1]
            movieUrlContent = movieUrlContent[5..-2]
                
            def manager = new ScriptEngineManager()
            def engine = manager.getEngineByName("JavaScript")

            String javascriptString = """
            var x = """ + movieUrlContent + """
            x
            """

            movieUrlContent = engine.eval(javascriptString)               
            itemUrl = movieUrlContent.find('file:"[^"]+"')
            itemLogo = movieUrlContent.find('image:"[^"]+"')
            if (itemUrl){
                itemUrl = itemUrl[6..-2]
                itemLogo = itemLogo[7..-2]
                found = true
            }
        }    
   
        //Try to extract stream from [movshare.net]
        if (vhost == 'movshare.net'){
            String movieUrl = 'http://www.movshare.net/mobile/?id=' + vid

            resourceUrl = new URL(movieUrl)
            String movieUrlContent = resourceUrl.getText()

            movieUrl = movieUrlContent.find('<source src="[^"]+.flv"')
            if (movieUrl)
            {
                itemUrl = movieUrl[13..-2]
                itemLogo = 'http://www.movshare.net/images/logo.png'
                found = true
            }
        }
        

        if (found)
            return [itemUrl, itemLogo, found]
        else
            return [null, null, false]
    }

    ContentURLContainer extractUrl(WebResourceItem item, PreferredQuality requestedQuality) {
        String url = item.getAdditionalInfo()['WebResourceItemUrl']
        URL resourceUrl = new URL(url);
        String content = openURL(resourceUrl, USER_AGENT)

        String itemLogo
        String itemUrl
        Boolean found = false

        def list
        list = (content =~ /javascript:show\('([^']+)','([^']+)', '([^']+)'\)/)
        for (def it: list){
            (itemUrl, itemLogo, found) = getStream(it[1], it[2], it[3])
            if (found) break
        }
        
        if (found)
            return new ContentURLContainer(fileType: MediaFileType.VIDEO, contentUrl: itemUrl, thumbnailUrl: itemLogo, live: false)
        else
            return null
    }


    WebResourceContainer extractItems(URL resourceUrl, int maxItems) {
        List<WebResourceItem> items = []
        int counter = 1
        String content = openURL(resourceUrl, USER_AGENT)
        
        String season = resourceUrl
        season = season.find(/season_\d+/)
        if (season)
            season = season[7..-1]
        
        String main_title = (content =~ /var main_title = "(.*)"/)[0][1]
        def list = (content =~ /show_season\("\d+","([^"]*)"/ )
        
        for (int i=0; (i < list.size() - 1); i++){
            String line = '|' + list[i][1] + '|'
            def temp = (line =~ /\|([^|]+)\|/)
            temp.each{
                def params = it[1].split(/_/)
                String itemUrl = BASE_URL + '/player/' + params[2] + '/' + main_title + '/season_' + params[0] + '/episode_' + params[1] + '/' +  URLEncoder.encode(params[3].replace(' ', "_")) + '/' 
                if (((counter <= maxItems) || (maxItems == -1)) && ((season == null) || (params[0] == season))){
                    counter++
                    WebResourceItem item = new WebResourceItem(title: ('s' + params[0].padLeft(2,'0') + '_e' + params[1].padLeft(2,'0')), additionalInfo: ['WebResourceItemThumbnailUrl':LOGO,'WebResourceItemUrl':itemUrl])
                    items << item
                }
            }
        }
        
        return new WebResourceContainer(title: main_title, thumbnailUrl: LOGO, items: items)
    }

    static WebResourceContainer testURL(String url, int itemCount = 2) {
        TubePlus extractor = new TubePlus();
        URL resourceUrl = new URL(url);
        println "getExtractorName : " + extractor.getExtractorName();
        println "getVersion : " + extractor.getVersion();
        println "extractorMatches : " + extractor.extractorMatches(resourceUrl);
        WebResourceContainer container = extractor.extractItems(resourceUrl, itemCount);
        println "extractItems : " + container.items.size();
        container.items.each{
            println it.title + "   : " + extractor.extractUrl(it, PreferredQuality.HIGH)
        }
//        println  container.items[5].title + "           : " + extractor.extractUrl(container.items[1], PreferredQuality.HIGH)
//        return container
    }


    static void main(args) {
        testURL("http://www.tubeplus.me/player/1250346/Psych/season_1",-1)
//        testURL("http://www.tubeplus.me/player/1006325/How_I_Met_Your_Mother/season_9",-1)
//        testURL("http://www.tubeplus.me/player/2129177/The_Big_Bang_Theory/season_7/",-1)
    }
}