import urllib,urllib2,re,xbmcplugin,xbmcgui,urlresolver,sys,xbmc,xbmcaddon,os,urlparse,cf,net
from t0mm0.common.addon import Addon
from metahandler import metahandlers

net = net.Net()
addon_id = 'plugin.video.hulubox'
selfAddon = xbmcaddon.Addon(id=addon_id)
addon = Addon(addon_id, sys.argv)
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id , 'fanart.jpg'))
icon = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
metaset = selfAddon.getSetting('enable_meta')
datapath= xbmc.translatePath(selfAddon.getAddonInfo('profile'))
try:os.mkdir(datapath)
except:pass
file_var = open(xbmc.translatePath(os.path.join(datapath, 'cookie.lwp')), "a")
cookie_file = os.path.join(os.path.join(datapath,''), 'cookie.lwp')


def CATEGORIES():
        addDir2('Recently Added','http://www.hulubox.com/category/all/',1,icon,fanart)
        addDir2('Action','http://www.hulubox.com/category/all/action',1,icon,fanart)
        addDir2('Adventure','http://www.hulubox.com/category/all/adventure',1,icon,fanart)
        addDir2('Comedy','http://www.hulubox.com/category/all/comedy',1,icon,fanart)
        addDir2('Crime','http://www.hulubox.com/category/all/crime',1,icon,fanart)
        addDir2('Drama','http://www.hulubox.com/category/all/drama',1,icon,fanart)
        addDir2('Horror','http://www.hulubox.com/category/all/horror',1,icon,fanart)
        addDir2('Thriller','http://www.hulubox.com/category/all/thriller',1,icon,fanart)
        addDir2('Years','url',4,icon,fanart)
        addDir2('Search','url',3,icon,fanart)

def YEARS():
        addDir2('1950-1999','http://www.hulubox.com/category/all/1950-1999/',1,icon,fanart)
        addDir2('2000-2004','http://www.hulubox.com/category/all/2000-2004/',1,icon,fanart)
        addDir2('2005-2010','http://www.hulubox.com/category/all/2005-2010/',1,icon,fanart)
        addDir2('2011','http://www.hulubox.com/category/all/2011/',1,icon,fanart)
        addDir2('2012','http://www.hulubox.com/category/all/2012/',1,icon,fanart)
        addDir2('2013','http://www.hulubox.com/category/all/2013',1,icon,fanart)
        addDir2('2014','http://www.hulubox.com/category/all/2014',1,icon,fanart)
        addDir2('2015','http://www.hulubox.com/category/all/2015',1,icon,fanart)
        addDir2('2016','http://www.hulubox.com/category/all/2016',1,icon,fanart)
           
def GETMOVIES(url,name):
        metaset = selfAddon.getSetting('enable_meta')
        link = open_url(url)
        match=re.compile('title="(.+?)" href="(.+?)">').findall(link)[2:][:-1]
        for name,url in match:
            if not 'malink' in name:    
                name=cleanHex(name)
                if metaset=='false':
                        addLink(name,url,100,icon,fanart)
                else: addDir(name,url,100,'',len(match),isFolder=False)
        try:
                url=re.compile("<link rel='next' href='(.+?)' />").findall(link)[0]
                addDir2('Next Page>>',url,1,icon,fanart)
        except: pass
        if metaset=='true':
                setView('movies', 'MAIN')
        else: xbmc.executebuiltin('Container.SetViewMode(50)')
        
def cleanHex(text):
    def fixup(m):
        text = m.group(0)
        if text[:3] == "&#x": return unichr(int(text[3:-1], 16)).encode('utf-8')
        else: return unichr(int(text[2:-1])).encode('utf-8')
    try :return re.sub("(?i)&#\w+;", fixup, text.decode('ISO-8859-1').encode('utf-8'))
    except:return re.sub("(?i)&#\w+;", fixup, text.encode("ascii", "ignore").encode('utf-8'))

def SEARCH():
    search_entered =''
    keyboard = xbmc.Keyboard(search_entered, 'Search HuluBox')
    keyboard.doModal()
    if keyboard.isConfirmed():
        search_entered = keyboard.getText().replace(' ','+')
    if len(search_entered)>1:
        url = 'http://www.hulubox.com/?s='+ search_entered
        link = open_url(url)
        GETMOVIES(url,name)

def PLAYLINK(name,url,iconimage):
        link = open_url(url)
        if 'youlol' in link:
                url=re.compile('<IFRAME SRC="(.+?)" FRAMEBORDER').findall(link)[0]
                link = open_url(url)
                url=re.compile('file:"(.+?)"').findall(link)
                for item in url:
                        if 'mp4' in item:url=item     
        else:
                stream_url=re.compile('"http://videomega.tv/validatehash.php\?hashkey=(.+?)"').findall(link)[0]
                stream_url='http://videomega.tv/validatehash.php?hashkey='+stream_url
                url = urlresolver.resolve(stream_url)
                url=url.replace('Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25','Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36')

        liz=xbmcgui.ListItem(name, iconImage=icon,thumbnailImage=icon); liz.setInfo( type="Video", infoLabels={ "Title": name } )
        xbmc.Player ().play(url, liz, False)

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
        return param

def addDir2(name,url,mode,iconimage,fanart,description=''):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': description } )
        liz.setProperty('fanart_image', fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

def addLink(name,url,mode,iconimage,fanart,description=''):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setProperty('fanart_image', fanart)
        liz.setInfo( type="Video", infoLabels={ "Title": name, 'plot': description } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
        return ok

def addDir(name,url,mode,iconimage,itemcount,isFolder=False):
        if metaset=='true':
            splitName=name.partition('(')
            simplename=""
            simpleyear=""
            if len(splitName)>0:
                simplename=splitName[0]
                simpleyear=splitName[2].partition(')')
            if len(simpleyear)>0:
                simpleyear=simpleyear[0]
            mg = metahandlers.MetaData()
            meta = mg.get_meta('movie', name=simplename ,year=simpleyear)
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&site="+str(site)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=iconimage)
            liz.setInfo( type="Video", infoLabels= meta )
            contextMenuItems = []
            contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
            liz.addContextMenuItems(contextMenuItems, replaceItems=True)
            if not meta['backdrop_url'] == '': liz.setProperty('fanart_image', meta['backdrop_url'])
            else: liz.setProperty('fanart_image', fanart)
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder,totalItems=itemcount)
            return ok
        else:
            u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&site="+str(site)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
            ok=True
            liz=xbmcgui.ListItem(name, iconImage=icon, thumbnailImage=icon)
            liz.setInfo( type="Video", infoLabels={ "Title": name } )
            liz.setProperty('fanart_image', fanart)
            liz.setProperty("IsPlayable","true")
            ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=isFolder)
            return ok
        
def open_url(url):
       link = cleanHex(net.http_GET(url).content)
       link = link.replace('\n','').replace('  ','')
       return link

def setView(content, viewType):
    if content:
        xbmcplugin.setContent(int(sys.argv[1]), content)
    if selfAddon.getSetting('auto-view')=='true':
        xbmc.executebuiltin("Container.SetViewMode(%s)" % selfAddon.getSetting(viewType) )

params=get_params(); url=None; name=None; mode=None; site=None; iconimage=None
try: site=urllib.unquote_plus(params["site"])
except: pass
try: url=urllib.unquote_plus(params["url"])
except: pass
try: name=urllib.unquote_plus(params["name"])
except: pass
try: mode=int(params["mode"])
except: pass
try: iconimage=urllib.unquote_plus(params["iconimage"])
except: pass

print "Site: "+str(site); print "Mode: "+str(mode); print "URL: "+str(url); print "Name: "+str(name)
print params

if mode==None or url==None or len(url)<1: CATEGORIES()
elif mode==1: GETMOVIES(url,name)
elif mode==2: GETTV(url,name)
elif mode==3: SEARCH()
elif mode==4: YEARS()
elif mode==100: PLAYLINK(name,url,iconimage)

xbmcplugin.endOfDirectory(int(sys.argv[1]))

