#!/usr/bin/env python
# Copyright 2010 Mackenzie Morgan <maco.m@ubuntu.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys, os, re

from PyQt4 import QtGui, QtCore
from PyKDE4.kdecore import (ki18n, i18n, KCmdLineArgs, KAboutData, KGlobal,
    KStandardDirs)
from PyKDE4.kdeui import (KApplication, KXmlGuiWindow, KStandardAction,
    KAction, KIcon)
from PyQt4.phonon import *

from gally.twoPanes import Ui_TwoPanes
from gally.LessonParser import LessonParser

HOME = os.environ['HOME']

class Gally(KXmlGuiWindow):
    '''A window with two panes, the left a scollArea, the right a QWidget.'''

    def showPrev(self):
        if (self.lastMove == "next"):
            self.signRev = reversed(
                self.lesson.signs[0:self.lesson.signs.index(self.sign)])

        self.sign = self.signRev.next()
        self.showSign(self.sign)
        self.lastMove = "prev"

        if (self.sign == self.lesson.signs[0]):
            self.goBack.setEnabled(False)

        if (self.sign != self.lesson.signs[-1]):
            self.goForward.setEnabled(True)

    def showNext(self):
        if (self.lastMove == "prev"):
            self.signIter = iter(
                self.lesson.signs[self.lesson.signs.index(self.sign):])

        if self.ui.stackedWidget.currentWidget() is self.ui.introPage:
            self.goBack.setEnabled(True)
            self.sign = self.signIter.next()
        else:
            self.sign = self.signIter.next()
        self.showSign(self.sign)
        self.lastMove = "next"

        if (self.sign == self.lesson.signs[-1]):
            self.goForward.setEnabled(False)

        if (self.sign != self.lesson.signs[0]):
            self.goBack.setEnabled(True)
            # ok really should go to quiz...

    def showSign(self, sign):
        if sign.displayType == "image":
            self.ui.stackedWidget.setCurrentWidget(self.ui.imageLesson)
            self.ui.img_wordTitle.setText(sign.name)
            self.ui.img_wordDescription.setText(sign.text)
            self.ui.img_lessonLabel.setPixmap(QtGui.QPixmap(sign.filename))
            if sign.hasContext == True:
                self.ui.img_exampleLabel.setPixmap(QtGui.QPixmap(sign.context))
                self.ui.img_exampleFrame.show()
            else:
                self.ui.img_exampleFrame.hide()
        elif sign.displayType == "video":
            self.ui.stackedWidget.setCurrentWidget(self.ui.videoLesson)
            self.ui.vid_wordTitle.setText(sign.name)
            self.ui.vid_wordDescription.setText(sign.text)
            self.playVid()

            if sign.hasContext == True:
                self.ui.vid_exampleLabel.setPixmap(QtGui.QPixmap(sign.context))
                self.ui.vid_exampleFrame.show()
            else:
                self.ui.vid_exampleFrame.hide()

    def playVid(self):
        src = Phonon.MediaSource(QtCore.QString(self.sign.filename))
        self.ui.vid_lessonPlayer.play(src)

    def playQuizVid(self):
        src = Phonon.MediaSource(QtCore.QString(self.sign.filename))
        self.ui.quizPlayer.play(src)

    def runLesson(self, lesson):
        self.ui.stackedWidget.setCurrentWidget(self.ui.introPage)
        self.ui.introTitle.setText(lesson.subject)
        self.ui.introText.setText(lesson.intro)
        self.goBack.setEnabled(False)
        self.goForward.setEnabled(True)
        self.signIter = iter(lesson.signs)
        self.lastMove = "next"

    def getLesson(self, item):
        if (item.text(0).contains(".")):
            num = int(re.split("\.",item.text(0))[0])
            parser = LessonParser(KGlobal.locale().languageList())
            #lang = item.parent
            langDir = self.languages[0].dir
            #print langDir
            try:
                self.lesson = parser.parseLessonFile(langDir,num)
                self.runLesson(self.lesson)
            except IOError:
                self.ui.stackedWidget.setCurrentWidget(self.ui.introPage)
                self.ui.introTitle.setText("ERROR")
                self.ui.introText.setText("Lesson definition is missing")
                self.goForward.setEnabled(False)
        else:
            self.ui.stackedWidget.setCurrentWidget(self.ui.introPage)
            self.ui.introTitle.setText(item.text(0))
            self.ui.introText.setText("")
            self.goBack.setEnabled(False)
            self.goForward.setEnabled(False)


    def __init__(self):
        """ Setup the program. """
        KXmlGuiWindow.__init__(self)

        self.ui = Ui_TwoPanes()
        myWidget = QtGui.QWidget()
        self.ui.setupUi(myWidget)
        self.setCentralWidget(myWidget)

        # Add a quit action
        KStandardAction.quit(app.quit, self.actionCollection())

        # Add a previous action
        self.goBack = KAction(KIcon("go-previous"),
            i18n("Show &previous sign"), self)
        self.goBack.setShortcut(QtGui.QKeySequence("Ctrl+P"))
        self.goBack.setWhatsThis(i18n("Go to previous sign"))
        self.actionCollection().addAction("back", self.goBack)
        self.goBack.triggered.connect(self.showPrev)

        # Add a next action
        self.goForward = KAction(KIcon("go-next"),
            i18n("Show &next sign"), self)
        self.goForward.setShortcut(QtGui.QKeySequence("Ctrl+N"))
        self.goForward.setWhatsThis(i18n("Go to next sign"))
        self.actionCollection().addAction("forward", self.goForward)
        self.goForward.triggered.connect(self.showNext)

        # Add the replay button's action
        self.ui.replayButton.setIcon(KIcon("media-playback-start"))
        self.ui.replayButton.clicked.connect(self.playVid)

        # And the Quiz replay button...
        self.ui.quizPlayButton.setIcon(KIcon("media-playback-start"))
        self.ui.quizPlayButton.clicked.connect(self.playQuizVid)

        # Set explanation labels in pages to wrap
        self.ui.introText.setWordWrap(True)
        self.ui.img_wordDescription.setWordWrap(True)
        self.ui.vid_wordDescription.setWordWrap(True)

        # Make image-holding labels always scale the images
        self.ui.img_lessonLabel.setScaledContents(True)
        self.ui.img_exampleLabel.setScaledContents(True)
        self.ui.vid_exampleLabel.setScaledContents(True)

        # Setup GUI
        self.ui.stackedWidget.setCurrentWidget(self.ui.introPage)
        self.setupGUI()


        # Init the data
        self.languages = []


        parser = LessonParser(KGlobal.locale().languageList())
        kst = KGlobal.dirs()
        gallyDirs = kst.findDirs("data", "gally")
        #langDirs = []
        #for d in gallyDirs:
        #    print d
        #    langDirs.append(os.walk(str(d)))
        #for lang in langDirs:
        #    for langthing in lang:
                #if (os.path.isfile(langthing[0])):
                 #   lang.remove(langthing)
                #print langthing[0]
        lang = None
        for dir in gallyDirs:
            # TODO: get rid of global when switch to multi-lang happens
            langDir = os.path.join(str(dir),"ASL")
            #print langDir
            if (os.path.exists(langDir)):
                if (os.path.isfile(os.path.join(langDir,"lessons.lang"))):
                    lang = parser.parseLanguageFile(langDir)
                    self.languages.append(lang)

                    # Intro page for the language
                    self.ui.stackedWidget.setCurrentWidget(self.ui.introPage)
                    self.ui.introTitle.setText(lang.name)
                    self.ui.introText.setText("")

                    topItem = QtGui.QTreeWidgetItem([lang.name])
                    topItem.setExpanded(True)
                    for less in lang.lessons:
                        childItem = QtGui.QTreeWidgetItem(
                            topItem, [str(less.lessonNum)+". "+less.subject])
                    self.ui.lessonTree.itemActivated.connect(self.getLesson)
                    self.ui.lessonTree.addTopLevelItem(topItem)
                    self.ui.lessonTree.expandItem(topItem)
        if (lang is None):
            self.ui.introTitle.setText("ERROR")
            self.ui.introText.setText("Missing language definitions.\nPlease download ASL lessons from http://launchpad.net/gally-asl")
        self.goBack.setEnabled(False)
        self.goForward.setEnabled(False)


if __name__ == "__main__":
    appName     = "gally" # when there's an icon, it's name goes here
    catalog     = ""
    programName = ki18n("Gally")
    version     = "0.5"
    description = ki18n("Sign language tutor")
    license     = KAboutData.License_GPL_V3
    copyright   = ki18n("(c) 2010 Mackenzie Morgan")
    text        = ki18n(
        "This application teaches vocabulary and grammar for sign languages.")
    homePage    = "http://launchpad.net/gally-project"
    bugEmail    = "maco.m@kubuntu.org"

    aboutData = KAboutData(appName, catalog, programName, version, description,
        license, copyright, text, homePage, bugEmail)
    aboutData.addAuthor(ki18n("Mackenzie Morgan"), ki18n("Lead Developer"),
        "maco.m@kubuntu.org", "")
    aboutData.addCredit(ki18n("Paul Hummer"), ki18n("Build system"),
        "", "http://theironlion.net")
    aboutData.addCredit(ki18n("Karen Rustad"), ki18n("Icon"),
            "", "http://www.littlegreenriver.com/")

    KCmdLineArgs.init(sys.argv, aboutData)

    app = KApplication()
    window = Gally()
    window.show()
    sys.exit(app.exec_())
