import xbmc,xbmcaddon,xbmcgui,xbmcplugin,os,sys,re,urllib,urllib2
import pyxbmct.addonwindow as pyxbmct
from addon.common.addon import Addon

addon_id = 'plugin.program.readcomics'
selfAddon = xbmcaddon.Addon(id=addon_id)
addon = Addon(addon_id, sys.argv)
icon = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'fanart.jpg'))

def START(url):
        global nextpage
        global prevpage
        global Icon
        global Next
        global Previous
        global FirstPage
        FirstPage=url
        link=open_url(url)
        comicpage=re.compile('src="(.+?)" data-width=').findall(link)[0]
        nextpage=re.compile('<a href="(.+?)" class="nav next">Next</a>').findall(link)[0]
        try:
                prevpage=re.compile('<a href="(.+?)" class="nav prev">Previous</a>').findall(link)[0]
        except:pass
	window= pyxbmct.AddonDialogWindow('')
        artpath = '/resources/art'
        button_focus = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id + artpath, 'button_focus1.png'))
        Qbutton_focus = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id + artpath, 'Qbutton_focus1.png'))
        button_no_focus = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id + artpath, 'button_no_focus1.png'))
        bg = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id + artpath, 'main-bg1.png'))
        window.setGeometry(1300, 720, 100, 50)
        background=pyxbmct.Image(bg)
        window.placeControl(background, -10, -10, 130, 70)
        text = '0xFF000000'
	Previous = pyxbmct.Button('<< Previous Page',focusTexture=button_focus,noFocusTexture=button_no_focus,textColor=text,focusedColor=text)
	Next = pyxbmct.Button('Next Page >>',focusTexture=button_focus,noFocusTexture=button_no_focus,textColor=text,focusedColor=text)
	Quit = pyxbmct.Button('<< Close Comic >>',focusTexture=Qbutton_focus,noFocusTexture=button_no_focus,textColor=text,focusedColor=text)
	Icon=pyxbmct.Image(comicpage)#, aspectRatio=2)
	window.placeControl(Previous ,102, 1,  6, 10)
	window.placeControl(Next ,102, 40, 6, 10)
	window.placeControl(Quit ,102, 21, 6, 10)
	window.placeControl(Icon, 0, 13, 100, 25)
	Previous.controlRight(Next)
	Previous.controlUp(Quit)
	window.connect(Previous,PREVIOUSPAGE)
	window.connect(Next,NEXTPAGE)   
	Previous.setVisible(False)
        window.setFocus(Next)
        Previous.controlRight(Quit)
        Quit.controlLeft(Previous)
        Quit.controlRight(Next)
        Next.controlLeft(Quit)
	window.connect(Quit, window.close)
	window.doModal()
	del window
        
def NEXTPAGE():
        global nextpage
        global prevpage
        global Icon
        global link
        Previous.setVisible(True)
        link=open_url(nextpage)
        comicpage=re.compile('src="(.+?)" data-width=').findall(link)[0]
        nextpage=re.compile('<a href="(.+?)" class="nav next">Next</a>').findall(link)[0]
        prevpage=re.compile('<a href="(.+?)" class="nav prev">Previous</a>').findall(link)[0]
        Icon.setImage(comicpage)
        
def PREVIOUSPAGE():
        global nextpage
        global prevpage
        global Icon
        global link               
        Previous.setVisible(True)
        link=open_url(prevpage)
        comicpage=re.compile('src="(.+?)" data-width=').findall(link)[0]
        nextpage=re.compile('<a href="(.+?)" class="nav next">Next</a>').findall(link)[0]
        prevpage=re.compile('<a href="(.+?)" class="nav prev">Previous</a>').findall(link)[0]     
        Icon.setImage(comicpage)
            
def HOME():
        addDir('Popular Comics','http://www.comicextra.com/popular-comic',1,icon,icon)
        addDir('Latest Releases','http://www.comicextra.com/comic-updates',4,icon,icon)
        addDir('Comic List','http://www.comicextra.com/comic-list',5,icon,icon)
        addDir('Search','http://www.comicextra.com/comic-search?key=',6,icon,icon)

def GET_POP_COMICS(url):
        link=open_url(url)
        match=re.compile('<a href="(.+?)" class="image"><img src="(.+?)" alt="Read(.+?) online" /></a>').findall(link)
        for url,thumb,name in match:
                thummb=thumb.replace('/small/','/large/')
                addDir(name,url,2,thumb,thumb)
        try:
                np=re.compile('<a href="(.+?)">Next</a>').findall(link)[0]                                                  
                addDir('Next Page >>',np,1,icon,icon)
        except: pass

def GET_NEW_COMICS(url):
        link=open_url(url)
        match=re.compile('<a href="(.+?)">(.+?)</a>').findall(link)
        for url,name in match:
                if 'chapter'in url:
                        addLink(name,url,3,icon,icon)

                                                                 
def GET_ISSUE(name,url,iconimage):
        link=open_url(url)
        match=re.compile('href="(.+?)">(.+?)</a>').findall(link)
        for url, iname in match:
                if '#' in iname:
                        addLink(iname,url,3,iconimage,iconimage)

def GET_COMIC_LIST(url):
        link=open_url(url)
        match=re.compile('<li><a href="(.+?)">(.+?)</a>').findall(link)
        for url,name in match:
                if 'comic/'in url:
                        addDir(name,url,2,icon,icon)
        
def SEARCH(url):
    search_entered =''
    title='[COLOR gold]Search[/COLOR]'
    keyboard = xbmc.Keyboard(search_entered,title)
    keyboard.doModal()
    if keyboard.isConfirmed():
	search_entered = keyboard.getText().replace(' ','+')
    if len(search_entered)>1:
	url = url+search_entered
	GET_POP_COMICS(url)
    else:quit()
    
def open_url(url):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        return link

def addDir(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.strip(), 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.strip(), 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=False)
        return ok

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

params=get_params(); url=None; name=None; mode=None; site=None; iconimage=None; description=None

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
try: description=urllib.unquote_plus(params["description"])
except: pass

if mode==None or url==None: HOME()
elif mode==1:GET_POP_COMICS(url)
elif mode==2:GET_ISSUE(name,url,iconimage)
elif mode==3:START(url)
elif mode==4:GET_NEW_COMICS(url)
elif mode==5:GET_COMIC_LIST(url)
elif mode==6:SEARCH(url)

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