#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import lxml.html

from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
from PySide.QtNetwork import *

PROGRAM_NAME = "The IMDb Game"
AUTHOR = "DarkRanger <darkranger.no-ip.org>"
VERSION = "20160910"
LICENSE = "GNU General Public License"
DEFAULT_WIDTH = 210
DEFAULT_HEIGHT = 400
IMDB_MAIN = "http://www.imdb.com/"
IMDB_RANDOM = "http://www.imdb.com/random/title"

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.count = -1
        self.game = False
        self.title = ""
        self.title_url = ""
        self.initUI()
        
    def initUI(self):
        self.timer = QTimer(self)
        vbox = QGridLayout()
        
        self.blankImage = QImage(190, 300, QImage.Format_ARGB32)
        self.blankImage.fill(qRgb(255,255,255))
        
        self.posterLabel = QLabel()
        vbox.addWidget(self.posterLabel, 0,0)
        self.posterLabel.setPixmap(QPixmap.fromImage(self.blankImage))
        
        self.startButton = QPushButton("New Game")
        vbox.addWidget(self.startButton, 1,0)
        self.aboutButton = QPushButton("About")
        vbox.addWidget(self.aboutButton, 2,0)
        
        self.statusBar = QStatusBar()
        vbox.addWidget(self.statusBar, 3,0)
        
        self.hidden_browser = QWebView()
        self.visible_browser = QWebView()
        self.visible_browser.setWindowTitle(PROGRAM_NAME)
        #self.visible_browser.resize(800, 600)
        
        self.connect(self.hidden_browser, SIGNAL("loadFinished(bool)"), self.newGame)
        self.connect(self.visible_browser, SIGNAL("urlChanged(QUrl)"), self.score)
        self.connect(self.startButton, SIGNAL("clicked()"), self.start)
        self.connect(self.aboutButton, SIGNAL("clicked()"), self.about)
        self.connect(self.timer, SIGNAL("timeout()"), self.timeoutCheck)
        
        self.setLayout(vbox)
        self.timer.start(10000)
    
    def urlCheck(self, url):
        if "ref_=nv_sr" in url:
            return False
        if not url.startswith(IMDB_MAIN):
            return False
            
        return True
        
    def replyFinished(self, reply):
        image = QImage.fromData(reply.readAll())
        pixmap = QPixmap.fromImage(image)
        self.posterLabel.setPixmap(pixmap)
        
    def loadPoster(self, src):
        #src = "http://ia.media-imdb.com/images/M/MV5BMTQ0ODgzNjg2MV5BMl5BanBnXkFtZTgwNDkxMzc3MDE@._V1_UX182_CR0,0,182,268_AL_.jpg"
        manager = QNetworkAccessManager(self)
        manager.finished[QNetworkReply].connect(self.replyFinished)
        manager.get(QNetworkRequest(QUrl(src)))
        
    def newGame(self):
        try:
            self.count = -1
            self.title_url = self.hidden_browser.url().toString()
            page = self.hidden_browser.page().mainFrame().toHtml()
            html = lxml.html.fromstring(page)
            self.title = html.find(".//title").text.replace(" - IMDb", "")
            div = html.find_class("poster")[0]
            img = div.find("a/img")
            src = img.attrib["src"]
            print(self.title)
            print(self.title_url)
            self.loadPoster(src)
            self.guiEnabled(True)
            self.visible_browser.load(QUrl(IMDB_MAIN))
            self.visible_browser.show()
            
        except (Exception) as error:
            print(error)
            msb = QMessageBox.information(self, "Message","Please try again.")
            self.guiEnabled(True)
        
    def start(self):
        print("New Game")
        self.game = True
        self.guiEnabled(False)
        #self.hidden_browser.load(QUrl("http://www.imdb.com/title/tt0831387/"))
        self.hidden_browser.load(QUrl(IMDB_RANDOM))

    def score(self):
        url = self.visible_browser.url().toString()
        
        if self.game == True:
            if self.urlCheck(url):
                self.count = self.count + 1
        
                if self.count > 0:
                    print(url)
                    self.statusBar.showMessage("Clicked: %d" % self.count)
                else:
                    self.statusBar.showMessage(self.title)
                
                if self.title_url in url:
                    self.game = False
                    print("(%d)Found!" % self.count)
                    msb = QMessageBox.information(self, "Message",
                    "Congratulations, you have found the correct title.")
            else:
                self.game = False
                msb = QMessageBox.information(self, "Message", "You can not do this.")
        else:
            msb = QMessageBox.information(self, "Message",
            "Please start a new game.")
            
    def timeoutCheck(self):
        if self.game == True and self.title_url == "":
            self.hidden_browser.reload()

    def guiEnabled(self, boolean):
        if boolean == True:
            self.startButton.setText("New Game")
        else:
            self.startButton.setText("Loading")
            
        self.startButton.setEnabled(boolean)
    
    def about(self):
        msb = QMessageBox.information(self, "About",
        "%s\nAuthor: %s\nLicense: %s\nVersion: %s" % (PROGRAM_NAME, AUTHOR, LICENSE, VERSION))
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setWindowTitle("Menu")
    window.setFixedSize(DEFAULT_WIDTH, DEFAULT_HEIGHT)
    window.show()
    app.exec_()
    sys.exit()
    
