import pickle
import time
import locale

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from about_ui import Ui_AboutDialog
from .. import version
__version__ = version.__version__
import dateutil.parser as dparser

class MovieItemWidget(QFrame):
    def __init__(self, movie, trailerFilter, *args):
        QWidget.__init__(self, *args)

        self.movie = movie
        self.filter = trailerFilter

        self.titlebox = QHBoxLayout()
        locale.setlocale(locale.LC_ALL, "C")
        releaseDate=None
        if movie.releasedate:
            releaseDate = dparser.parse(movie.releasedate)
            locale.resetlocale()
            releaseDate = releaseDate.strftime("%x")
        titleLabel = QLabel("<h2>%s</h2> (Release date: %s)" %
        (movie.title, releaseDate), self)
        self.setFrameStyle(QFrame.Panel | QFrame.Sunken);

        self.titlebox.addWidget(titleLabel)
        self.titlebox.addStretch(1)

        middleArea = QHBoxLayout()
        self.posterLabel = QLabel("<img src=""/>", self)
        self.posterLabel.setMinimumSize(QSize(134,193))
        self.posterLabel.setMaximumSize(QSize(134,193))

        mainArea = QVBoxLayout()
        self.mainArea = mainArea
        if movie.genre:
            genStr = ", ".join(movie.genre)
        else:
            genStr = "Unknown"
        genre = QLabel("<b>Genre(s): </b>%s" % genStr)
        mainArea.addWidget(genre)
        studio = QLabel("<b>Studio: </b>%s" % movie.studio)
        mainArea.addWidget(studio)
        directors = QLabel("<b>Director(s): </b>%s" % movie.directors)
        mainArea.addWidget(directors)
        actors = QLabel("<b>Actors: </b>%s" % ", ".join(movie.actors))
        mainArea.addWidget(actors)
        actors.setWordWrap(True)
        mainArea.addStretch(1)

        middleArea.addWidget(self.posterLabel)
        middleArea.addLayout(mainArea)


        topLevelLayout = QVBoxLayout()
        topLevelLayout.addLayout(self.titlebox)
        topLevelLayout.addLayout(middleArea)
        self.setMinimumSize(400,150)
        self.setLayout(topLevelLayout)

    def refresh(self):

        movie = self.movie

        self.button_mapping = {}
        posterImage = QImage()
        posterImage.loadFromData(movie.poster)
        self.posterLabel.setPixmap(QPixmap.fromImage(posterImage))

        self.downloadButtons = QButtonGroup()
        self.downloadButtons.buttonClicked.connect(self.download)
        self.viewButtons = QButtonGroup()
        self.viewButtons.buttonClicked.connect(self.view)
        links = 0
        for trailerName in movie.trailerLinks:
            trailerURLS = movie.trailerLinks[trailerName]
            for trailerLink in trailerURLS:
                if not self.filter.visible(trailerLink):
                    links = links + 1
                    continue
                self._add_buttons(trailerName, trailerLink, links)
                links = links + 1

            desc = QLabel(movie.description)
            desc.setWordWrap(True)
            desc.setTextFormat(Qt.RichText)
            self.layout().addWidget(desc)

    def _add_buttons(self, trailerName, trailerLink, ids):
        lab = QLabel('<a href="%s">%s</a>' % (trailerLink, trailerName), self)
        hbox= QHBoxLayout()
        button=QPushButton("Download")
        self.downloadButtons.addButton(button, ids)
        self.button_mapping[ids] = trailerLink
        hbox.addStretch(1)
        hbox.addWidget(lab)
        hbox.addWidget(button)
        button=QPushButton("View")
        self.viewButtons.addButton(button, ids)
        hbox.addWidget(button)
        self.mainArea.addLayout(hbox)

    downloadClicked = pyqtSignal((QString, ))
    viewClicked = pyqtSignal((QString, ))

    def download(self, button):
        id = self.downloadButtons.id(button)
        self.downloadClicked.emit(self.button_mapping[id])

    def view(self, button):
        id = self.viewButtons.id(button)
        self.viewClicked.emit(self.movie.trailerLinks[id])


class PyTrailerSettings(QDialog):
    def __init__(self, config):
        QDialog.__init__(self)
        self.config = config
        label = QLabel(self.tr("&Download path"))
        self.downloadPath = QLineEdit(self)
        self.downloadPath.setText(config.get("DEFAULT","downloadDir"))
        label.setBuddy(self.downloadPath)

        browseBut = QPushButton(self.tr("&Browse"))
        browseBut.clicked.connect(self.browseDir)

        hbox = QHBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(self.downloadPath)
        hbox.addWidget(browseBut)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        hbox = QHBoxLayout()
        self.filters = [('all','.*mov.*'),
                   ('320x180',r'.*h320\.mov.*'),
                   ('480x204',r'.*h480\.mov.*'),
                   ('640x360',r'.*h640w\.mov.*'),
                   ('480p',r'.*480p\.mov.*'),
                   ('720p',r'.*720p\.mov.*'),
                   ('1080p',r'.*1080p\.mov.*')]
        activeFilters = pickle.loads(config.get("DEFAULT","filters"))
        filterLayout = QVBoxLayout()
        filterGroup = QGroupBox(self.tr("Trailer quality filter"))
        filterGroup.setLayout(filterLayout)
        vbox.addWidget(filterGroup)
        self.filterButtons = []
        for qual, filt in self.filters:
            active = False
            if filt in activeFilters:
                active = True
            option = QCheckBox(qual)
            option.setChecked(active)
            self.filterButtons.append(option)
            filterLayout.addWidget(option)

        self.filterButtons[0].clicked.connect(self.refreshFilters)
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.Cancel);

        self.connect(buttonBox, SIGNAL("accepted()"), self, SLOT("accept()"));
        self.connect(buttonBox, SIGNAL("rejected()"), self, SLOT("reject()"));
        vbox.addWidget(buttonBox)
        self.setLayout(vbox)
        self.refreshFilters()

    def refreshFilters(self):
        for button in self.filterButtons[1:]:
            button.setEnabled(not self.filterButtons[0].isChecked())


    def accept(self):
        self.config.set("DEFAULT","downloadDir",
                        str(self.downloadPath.text()))
        activeFilters = []
        ind = 0
        for button in self.filterButtons:
            if button.isChecked():
                activeFilters.append(self.filters[ind][1])
            ind = ind + 1
        self.config.set("DEFAULT","filters",pickle.dumps(activeFilters))
        QDialog.accept(self)

    def browseDir(self):
        directory = QFileDialog.getExistingDirectory(self,
                                                     QString(),
                                                     self.config.get("DEFAULT",
                                                                     "downloadDir"))
        if directory:
            self.downloadPath.setText(directory)


class PyTrailerAbout(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self)
        self.ui = Ui_AboutDialog()
        self.ui.setupUi(self)
        self._main  = parent
        self.ui.label_version.setText(__version__)
        self.connect(self.ui.buttonClose, SIGNAL("clicked(bool)"), self.close)

