#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
PowerSword
Author: DarkRanger <http://darkranger.no-ip.org/>
License: GNU General Public License
'''

import os, sys, re, shutil
import platform
import Sword
from PySide.QtCore import *
from PySide.QtGui import *

appdir = os.path.abspath(os.path.dirname(sys.argv[0]))
os.chdir(appdir)

PRODUCT = u"PowerSword"
VERSION = u"beta 0.2"
BUILD = u"BUILD 20130219"
FONT = "PMingLiU"
MODULE = "chiun"
ENCODING = "utf-8"
TEMPLATE_PATH  = "templates"
TEMPLATE_FILE = "template1.ppt"
ODP_OUTPUT = "new.odp"
EXAMPLE = u"請輸入經節（例如3:1-12）"
ODF = 0

ot_books = [u"創世記",  u"出埃及記", u"利未記", u"民數記", u"申命記", u"約書亞記", u"士師記", u"路得記", u"撒母耳記上", u"撒母耳記下", \
            u"列王紀上", u"列王紀下", u"歷代志上", u"歷代志下", u"以斯拉記", u"尼希米記", u"以斯帖記", u"約伯記", u"詩篇", u"箴言", \
            u"傳道書", u"雅歌", u"以賽亞書", u"耶利米書", u"耶利米哀歌", u"以西結書", u"但以理書", u"何西阿書", u"約珥書", u"阿摩司書", \
            u"俄巴底亞書", u"約拿書", u"彌迦書", u"那鴻書", u"哈巴谷書", u"西番雅書", u"哈該書", u"撒迦利亞書", u"瑪拉基書"]

nt_books = [u"馬太福音", u"馬可福音", u"路加福音", u"約翰福音", u"使徒行傳", u"羅馬書", u"哥林多前書", u"哥林多後書", u"加拉太書", u"以弗所書", \
            u"腓立比書", u"歌羅西書", u"帖撒羅尼迦前書", u"帖撒羅尼迦後書", u"提摩太前書", u"提摩太後書", u"提多書", u"腓利門書", u"希伯來書", u"雅各書", \
            u"彼得前書", u"彼得後書", u"約翰一書", u"約翰二書", u"約翰三書", u"猶大書", u"啟示錄"]
            
ot_indexes = ["Gen", "Exod", "Lev", "Num", "Deut", "Josh", "Judg", "Ruth", "1Sam", "2Sam", \
              "1Kgs", "2Kgs", "1Chr", "2Chr", "Ezra", "Neh", "Esth", "Job", "Ps", "Prov", \
              "Eccl", "Song", "Isa", "Jer", "Lam", "Ezek", "Dan", "Hos", "Joel", "Amos", \
              "Obad", "Jonah", "Mic", "Nah", "Hab", "Zeph", "Hag", "Zech", "Mal" ]

nt_indexes = ["Matt", "Mark", "Luke", "John", "Acts", "Rom", "1Cor", "2Cor", "Gal", "Eph", \
              "Phil", "Col", "1Thess", "2Thess", "1Tim", "2Tim", "Titus", "Phlm", "Heb", "Jas", \
              "1Pet", "2Pet", "1John", "2John", "3John", "Jude", "Rev"]

class Dialog(QDialog):
    def __init__(self):
        super(Dialog, self).__init__()
        self.initUI()
        
    def initUI(self):         
        self.setFixedSize(250,330)
        self.setWindowTitle(u"關於 " + PRODUCT)  
        vbox = QGridLayout()
        edit = QTextEdit()
        edit.setReadOnly(True)
        edit.setHtml("<b>" + PRODUCT + "</b><br>"
                     + VERSION + " " + BUILD + "<br>"
                     + "DarkRanger<br>&lt;darkranger.no-ip.org&gt;<br><br>"
                     + u"本工具包含<br>由下列人士/社群所發佈的元件:<br><br>"
                     + "<b>pysword</b><br>"
                     + "Kenneth Arnold<br>&lt;github.com/kcarnold/pysword&gt;<br><br>"
                     + "<b>The SWORD Project</b><br>"
                     + "&lt;www.crosswire.org&gt;<br><br>"
                     + "<b>ODFPY</b><br>"
                     + "&lt;joinup.ec.europa.eu/software/odfpy/home&gt;<br><br>")
                     
        edit.setAlignment(Qt.AlignCenter)
        vbox.addWidget(edit,0,0,1,3)
        edit.setFont(FONT)
        
        button = QPushButton(u"關閉")
        button.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        vbox.addWidget(button,1,1,1,3)
        button.setFont(FONT)
        button.clicked.connect(self.button_close)
        
        self.setLayout(vbox)        
        self.show()
        
    def button_close(self):
        self.close()
        
class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()      
        
    def initUI(self):
        vbox = QGridLayout()
        
        self.ot = QRadioButton(u"舊約")
        vbox.addWidget(self.ot,0,0)
        self.ot.setFont(FONT)
        
        self.nt = QRadioButton(u"新約")
        vbox.addWidget(self.nt,0,1)
        self.nt.setFont(FONT)
        
        self.combo = QComboBox(self)
        vbox.addWidget(self.combo,1,0,1,3)
        self.combo.setFont(FONT)
        
        self.edit = QLineEdit()
        self.edit.setPlaceholderText(EXAMPLE)
        vbox.addWidget(self.edit,2,0,1,3)
        self.edit.setFont(FONT)
        
        generate_button = QPushButton(u"產出")
        vbox.addWidget(generate_button,3,0,1,3)
        generate_button.setFont(FONT)
        
        about_button = QPushButton(u"關於")
        about_button.setFont(FONT)
        vbox.addWidget(about_button,4,0,1,3)
        
        self.connect(self.ot, SIGNAL("toggled(bool)"), self.otToggled)
        self.connect(self.nt, SIGNAL("toggled(bool)"), self.ntToggled)
        self.connect(generate_button, SIGNAL("clicked()"), self.generate_buttonPushed)
        self.connect(about_button, SIGNAL("clicked()"), self.about_buttonPushed)
        self.connect(self.edit, SIGNAL("returnPressed()"), self.generate_buttonPushed)
        
        self.setLayout(vbox)   
        
    def otToggled(self, toggled):
        if toggled:
            self.combo.clear()
            for x in range (0,39):
                self.combo.addItem(ot_books[x])
       
    def ntToggled(self, toggled):
        if toggled:
            self.combo.clear()
            for x in range (0,27):
                self.combo.addItem(nt_books[x])

    def generate_buttonPushed(self):
        input_text = self.edit.text()
        if self.ot.isChecked() or self.nt.isChecked():
           if input_text.find(":") != -1 :
               q = QMessageBox.question(self, u"訊息", u"是否使用 ODF 模式？", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
               if q == QMessageBox.No and platform.system() == "Windows":
                   import win32com.client
                   ODF = 0
               else:
                   from odf.opendocument import OpenDocumentPresentation
                   from odf.style import Style, MasterPage, PageLayout, PageLayoutProperties, TextProperties, GraphicProperties, ParagraphProperties, DrawingPageProperties
                   from odf.text import P
                   from odf.draw  import Page, Frame, TextBox, Image
                   ODF = 1
                   
               if self.ot.isChecked():
                   book = ot_indexes[self.combo.currentIndex()]
                   title = ot_books[self.combo.currentIndex()]
               if self.nt.isChecked():
                   book = nt_indexes[self.combo.currentIndex()]    
                   title = nt_books[self.combo.currentIndex()]
                 
               convert = input_text.split(":")
               chapter = convert[0]
              
               if convert[1].find("-") != -1 :
                   convert2 = convert[1].split("-")
                   begin = int(convert2[0])
                   end = int(convert2[1])
                   total = (end - begin) + 1                 
               else:
                   begin = int(convert[1])
                   total = 1
                 
               if ODF == 0:    
                   if os.path.exists(os.path.abspath(os.path.join(appdir,TEMPLATE_PATH,TEMPLATE_FILE))):
                       shutil.copyfile(os.path.abspath(os.path.join(appdir,TEMPLATE_PATH,TEMPLATE_FILE)), os.path.abspath(os.path.join(appdir,"new.ppt")))
                       try:
                           powerpoint = win32com.client.gencache.EnsureDispatch("PowerPoint.Application")
                           powerpoint.Visible = True
              
                           path = os.path.abspath(os.path.join(appdir,"new.ppt"))
                           ppt = powerpoint.Presentations.Open(path)
              
                           if total > 1 :
                               for x in range (1,total):
                                   ppt.Slides(1).Copy()
                                   ppt.Slides.Paste()
              
                           for x in range (0, total):
                               word = Sword.result(MODULE, book, chapter, str(begin + x))
                               ppt.Slides(x +1).Shapes.Title.TextFrame.TextRange.Text = title + " " + str(chapter) + ":" + str(begin + x)
                               ppt.Slides(x +1).Shapes.Placeholders(2).TextFrame.TextRange.Text = word.decode(ENCODING)
                               
                       except Exception, error: 
                           print str(error)
                           msb = QMessageBox.information(self, u"訊息", u"PPT 產出作業失敗，請確認系統已安裝 PowerPoint")                                    
                   else:
                       msb = QMessageBox.information(self, u"訊息", u"簡報範本不存在：" + TEMPLATE_FILE)
                     
               else:
                   #Code based on odfpy/examples/photoalbum.py:
                   try:
                       doc = OpenDocumentPresentation()
                       pagelayout = PageLayout(name="layout1")
                       doc.automaticstyles.addElement(pagelayout)
                       pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt",pageheight="600pt", printorientation="landscape"))
                       titlestyle = Style(name="titlestyle", family="presentation")
                       titlestyle.addElement(ParagraphProperties(textalign="left"))
                       titlestyle.addElement(TextProperties(fontsize="34pt", textunderlinestyle="solid"))
                       titlestyle.addElement(GraphicProperties(fillcolor="#ffff99"))
                       doc.styles.addElement(titlestyle)
                 
                       textstyle = Style(name="textstyle", family="presentation")
                       textstyle.addElement(ParagraphProperties(textalign="left"))
                       textstyle.addElement(TextProperties(fontsize="34pt"))
                       textstyle.addElement(GraphicProperties(fillcolor="#ffff99"))
                       doc.styles.addElement(textstyle)     
                 
                       dpstyle = Style(name="dp1", family="drawing-page")
                       dpstyle.addElement(DrawingPageProperties(transitiontype="automatic",transitionstyle="move-from-top", duration="PT5S"))
                       doc.automaticstyles.addElement(dpstyle)                
                 
                       masterpage = MasterPage(name="master1", pagelayoutname=pagelayout)
                       doc.masterstyles.addElement(masterpage)
                 
                       for x in range (0, total):
                           word = Sword.result(MODULE, book, chapter, str(begin + x))
                           page = Page(stylename=dpstyle, masterpagename=masterpage)
                           doc.presentation.addElement(page)
                 
                           titleframe = Frame(stylename=titlestyle, width="720pt", x="40pt", y="40pt")
                           page.addElement(titleframe)
                           textbox = TextBox()
                           titleframe.addElement(textbox)
                           textbox.addElement(P(text=title + " " + str(chapter) + ":" + str(begin + x)))

                           textframe = Frame(stylename=textstyle, width="720pt", x="40pt", y="120pt")
                           page.addElement(textframe)
                           textbox2 = TextBox()
                           textframe.addElement(textbox2)
                           textbox2.addElement(P(stylename=textstyle, text=word.decode(ENCODING)))
   
                       doc.save(ODP_OUTPUT)
                       msb = QMessageBox.information(self, u"訊息", u"ODP 產出作業完成，檔名為 " + ODP_OUTPUT)
                   except Exception, error: 
                       print str(error)
                       msb = QMessageBox.information(self, u"訊息", u"ODP 產出作業失敗")                
           else:
               msb = QMessageBox.information(self, u"訊息", u"請輸入正確格式")

    def about_buttonPushed(self):  
        about = Dialog()
        about.exec_()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window1 = MainWindow()
    window1.setWindowTitle(PRODUCT)
    window1.setFixedSize(220,250)
    window1.show()
    app.exec_()
    sys.exit()
