class MoviePreview():
    def __init__(self, session):
        self.onHide.append(self.hideDialog)
        self["CoverPreview"] = Pixmap()
        self["backdrop"] = Pixmap()
        self.old_service = None
        self.working = False
        self.picParam = None
        self.picload = PicLoader()
        self.picload.addCallback(self.showPreviewCallback)
        self.backdrop = PicLoader()
        self.backdrop.addCallback(self.showBackdropCallback)
        self.onLayoutFinish.append(self.layoutFinish)
        self.onClose.append(self.__onClose)

    def __onClose(self):
        self.picload.destroy()
        self.backdrop.destroy()
    
    def layoutFinish(self):
        sc = AVSwitch().getFramebufferScale()
        self.picload.setPara((self["CoverPreview"].instance.size().width(), self["CoverPreview"].instance.size().height(), sc[0], sc[1], False, 1, "#ff000000"))
        self.backdrop.setPara((self["backdrop"].instance.size().width(), self["backdrop"].instance.size().height(), sc[0], sc[1], False, 1, "#ff000000"))

    def loadPreview(self, serviceref):
        self.hideDialog()
        if serviceref is None:
            empty = gPixmapPtr()
            self["CoverPreview"].instance.setPixmap(empty)
            self["backdrop"].hide()
            return
        path = serviceref.getPath()
        if serviceref.flags & eServiceReference.mustDescent:
            # directory
            if fileExists(path + ".jpg"):
                path += ".jpg"
            elif config.AdvancedMovieSelection.usefoldername.value:
                path = path[:-1] + ".jpg"
            else:
                path = path + "folder.jpg"
        elif os.path.isfile(path):
            # file service
            path_s = os.path.splitext(path)[0]
            path = path_s + ".jpg"
        else:   
            # structure service
            path = path + ".jpg"
        
        # load cover or provider icon
        self.working = True
        if fileExists(path):
            self.picload.startDecode(path)
            return
        series_path = os.path.join(os.path.dirname(path), "series.jpg")
        if fileExists(series_path):
            self.picload.startDecode(series_path)
            return
        # cover for serienrecorder plugin
        dir_name = os.path.dirname(path)
        series_path = os.path.join(dir_name,  os.path.basename(dir_name) + ".jpg")
        if fileExists(series_path):
            self.picload.startDecode(series_path)
            return
        if serviceref.getPath().endswith(".ts") and config.AdvancedMovieSelection.show_picon.value:
            picon = getServiceInfoValue(serviceref, iServiceInformation.sServiceref).rstrip(':').replace(':', '_') + ".png"
            piconpath = os.path.join(config.AdvancedMovieSelection.piconpath.value, picon)
            if fileExists(piconpath):
                self.picload.startDecode(piconpath)
                return
        cover_path = os.path.join(os.path.dirname(path), "cover.jpg")
        if fileExists(cover_path):
            self.picload.startDecode(cover_path)
        else:
            self.picload.startDecode(getNocover())
    
    def loadBackdrop(self, serviceref):
        self.backdrop_load = False
        if serviceref is None or not config.AdvancedMovieSelection.show_backdrop.value:
            self["backdrop"].hide()
            return

        if serviceref.flags & eServiceReference.mustDescent:
            backdrop_file = os.path.join(os.path.dirname(serviceref.getPath()), ".backdrop.jpg")
            if fileExists(backdrop_file):
                self.backdrop_load = True
                self.backdrop.startDecode(backdrop_file)
            else:
                self["backdrop"].hide()
            return
        
        path = serviceref.getPath()
        if os.path.isfile(path):
            # file service
            path_s = os.path.splitext(path)[0]
            backdrop_file = path_s + ".backdrop.jpg"
        else:
            # structure service
            backdrop_file = path + ".backdrop.jpg"
        
        # load backdrop
        if backdrop_file is not None and fileExists(backdrop_file):
            self.backdrop_load = True
            self.backdrop.startDecode(backdrop_file)
            return
        backdrop_file = os.path.join(os.path.dirname(path), "backdrop.jpg")
        if fileExists(backdrop_file):
            self.backdrop_load = True
            self.backdrop.startDecode(backdrop_file)
        else:
            self["backdrop"].hide()

    def showPreviewCallback(self, picInfo=None):
        if picInfo:
            ptr = self.picload.getData()
            if ptr != None and self.working:
                self["CoverPreview"].instance.setPixmap(ptr)
        self.working = False

    def showBackdropCallback(self, picInfo=None):
        if picInfo:
            ptr = self.backdrop.getData()
            if ptr != None and self.backdrop_load:
                self["backdrop"].instance.setPixmap(ptr)
                self["backdrop"].show()
        self.backdrop_load = False

    def hideDialog(self):
        self.working = False
class DownloadMovies(Screen):
    def __init__(self, session, items, service=None):
        Screen.__init__(self, session)
        self.skinName = "AdvancedMovieSelectionDownload"
        self.onShow.append(self.selectionChanged)
        self.onClose.append(self.__onClose)
        self.service = service
        self["logo"] = Pixmap()  
        self["info"] = Label()
        self["title"] = Label()
        self["poster"] = Pixmap()
        self["poster"].hide()
        self["description"] = ScrollLabel()
        self["key_red"] = Button(_("Cancel"))
        self["key_green"] = Button("")
        self["key_yellow"] = Button("")
        self["key_yellow"] = Label(_("Manual search"))
        if service is not None:
            self["key_green"] = Label(_("Save infos/cover"))
        else:
            self["key_green"] = Label(_("Background"))
            self["key_yellow"].hide()

        self["ActionsMap"] = ActionMap(["SetupActions", "ColorActions"],
         {
          "ok": self.titleSelected,
          "green": self.titleSelected,
          "red": self.__cancel,
          "yellow": self.editTitle,
          "cancel": self.__cancel,
          "left": self.scrollLabelPageUp,
          "right": self.scrollLabelPageDown
          }, -1)
        self.onShown.append(self.setWindowTitle)
      
        self.l = []
        self["list"] = MenuList(self.l)
        self["list"].onSelectionChanged.append(self.selectionChanged)
        
        self.picload = PicLoader()
        self.picload.addCallback(self.paintPosterPixmap)

        self.movie_title = ""
        if self.service is not None:
            self.movie_title = ServiceCenter.getInstance().info(self.service).getName(self.service)
            self.progressTimer = xTimer()
            self.progressTimer.addCallback(self.refresh)
            self.progressTimer.start(50, True)
            return

        if service is not None:
            items = [(service,)]
        global fetchingMovies
        if fetchingMovies is None or (fetchingMovies is not None and fetchingMovies.finished):
            fetchingMovies = FetchingMovies(session, items)
        else:
            fetchingMovies.cancel = False
        self.progressTimer = xTimer()
        self.progressTimer.addCallback(self.updateProgress)
        self.progressTimer.start(250, False)
        fetchingMovies.is_hidden = False

    def __onClose(self):
        self.picload.destroy()

    def setWindowTitle(self):
        self.setTitle(_("Search for %s, please wait...") % (self.movie_title))
        self["logo"].instance.setPixmapFromFile(getIconPath("tmdb_logo.png"))

    def scrollLabelPageUp(self):
        self["description"].pageUp()

    def scrollLabelPageDown(self):
        self["description"].pageDown()
    
    def paintPosterPixmap(self, picInfo=None):
        ptr = self.picload.getData()
        if ptr != None:
            self["poster"].instance.setPixmap(ptr)
            self["poster"].show()
    
    def __cancel(self):
        global fetchingMovies
        if fetchingMovies is not None:
            fetchingMovies.cancel = True
        self.close()

    def __hide(self):
        if fetchingMovies is not None:
            fetchingMovies.is_hidden = True
        self.close()
        
    def updateProgress(self):
        self.setTitle(_("Automatic search and save, please wait..."))
        current = 0
        total = 0
        movie_title = ""
        if fetchingMovies is not None:
            current = fetchingMovies.current
            total = fetchingMovies.total
            movie_title = fetchingMovies.movie_title
        self["info"].setText(_("Processing:") + " %d/%d" % (current, total))
        if fetchingMovies is not None and not fetchingMovies.finished:
            self["title"].setText(_("Current Movie: %s") % movie_title)
        else:
            self.setTitle(_("Automatic search and save"))
            self["title"].setText(_("Automatic search and save finished."))
            self["key_green"].setText(_("OK"))
            self.progressTimer.stop()

    def refresh(self):
        self.refreshMovieTitle(self.movie_title)  

    def refreshMovieTitle(self, title):
        self.movie_title = movie_title = title
        self["title"].setText(_("Searchtitle: %s") % movie_title)
        self["info"].setText(_("Filename: %s") % os.path.basename(self.service.getPath()))
        self.setTitle(_("Search result(s) for %s") % (movie_title))
        try:
            results = tmdb.searchMovie(movie_title)
        except:
            results = []
        if len(results) == 0:
            self.setTitle(_("Nothing found for: %s") % (movie_title))
            self["key_green"].setText(_("OK"))
            print "No info found for: " + movie_title
            return False

        self.l = []
        for movie in results:
            try:
                self["key_green"].setText(_("Save infos/cover"))
                released = str(movie.ReleaseDate.year)
                if released:
                    self.l.append((movie.Title + " - " + released, movie))
                else:
                    self.l.append((movie.Title, movie))
            except:
                pass

        self["list"].setList(self.l)

    def titleSelected(self):
        current = self["list"].l.getCurrentSelection()
        if self.service is not None and current:
            writeEITex(self.service.getPath(), current[1])
        self.__hide()        
    
    def selectionChanged(self):
        self["poster"].hide()
        current = self["list"].l.getCurrentSelection()
        if current:
            try:
                movie = current[1]
                self["description"].setText("%s - %s\n\n%s" % (str(movie.Title), str(movie.ReleaseDate), movie.Overview))
                jpg_file = "/tmp/preview.jpg"
                cover_url = movie.poster_url
                if cover_url is not None:
                    downloadCover(cover_url, jpg_file, True)
                else:
                    jpg_file = getNocover()
                sc = AVSwitch().getFramebufferScale()
                self.picload.setPara((self["poster"].instance.size().width(), self["poster"].instance.size().height(), sc[0], sc[1], False, 1, "#ff000000"))
                self.picload.startDecode(jpg_file)
            except Exception, e:
                print e