# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtCore, QtGui
from qgis.core import *
from qgis.gui import *
from DescriptUi import Ui_Form
from ClickFeature import ClickFeature
from datetime import datetime
import os
import os.path
import common
import const
import glob

# ダイアログクラス
class DescriptDialog(QWidget, Ui_Form):

    def __init__(self, iface):
        QWidget.__init__(self)

        self.iface = iface
        self.canvas = self.iface.mapCanvas()

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.btnPdf.setIcon(QIcon(":/plugins/HydropowerPotential/icon_print.png"))
        self.ui.btnPdf.released.connect(self.print_map)
        self.ui.btnClipZone.released.connect(self.clip_zone)

        #マップツールの定義
        self.descriptMapTool = ClickFeature(self.canvas, pickMode='all')
        self.descriptMapTool.geomIdentified.connect(self.showAttribute)
        #self.descriptMapTool.deactivated.connect(self.erase_line)
        self.canvas.setMapTool(self.descriptMapTool)

        self.erase_line()

        #テンポラリーレイヤー
        self.line_vl = QgsVectorLayer("LineString?crs=epsg:4612", u"ライン", "memory")
        renderer = self.line_vl.rendererV2()
        symbol = QgsLineSymbolV2.createSimple({u'line_color': u'255,0,0,128',u'line_width': u'1.6'})
        renderer.setSymbol(symbol)
        QgsMapLayerRegistry.instance().addMapLayers([self.line_vl],False)
        self.line_pr = self.line_vl.dataProvider()

        self.point_vl = QgsVectorLayer("Point?crs=epsg:4612", u"ポイント", "memory")
        renderer = self.point_vl.rendererV2()
        symbol = QgsMarkerSymbolV2.createSimple({u'color': u'255,0,0,128',u'size': u'3'})
        renderer.setSymbol(symbol)
        QgsMapLayerRegistry.instance().addMapLayers([self.point_vl],False)
        self.point_pr = self.point_vl.dataProvider()

        self.tree_root = QgsProject.instance().layerTreeRoot()
        self.group_vl = self.tree_root.insertGroup(0, const.TEMP_GROUP_NAME)
        self.group_vl.addLayer(self.point_vl)
        self.group_vl.addLayer(self.line_vl)
        self.group_vl.setExpanded(False)

        self.ui.grpHint.setVisible(True)
        self.ui.grpLink.setVisible(False)
        self.ui.grpZone.setVisible(False)
        self.ui.btnPdf.setVisible(False)
        self.ui.btnClipZone.setVisible(False)

    def showAttribute(self, layer, feature, event=""):
        #もともと選択されていたアイテムは削除
        self.point_vl.startEditing()
        self.line_vl.startEditing()
        common.deleteAllFeature(self.point_vl)
        common.deleteAllFeature(self.line_vl)

        if layer.name() == const.ZONE_LYR_NAME:
            self.point_pr.addFeatures( [ feature ] )

            common.setText(self.ui.z_SegmentID, feature["SegmentID"], "int")
            common.setText(self.ui.z_Elevation, feature["Elevation"], "int")
            common.setText(self.ui.z_AccumWSA, feature["AccumWSA"], "flt1")
            common.setText(self.ui.z_Qmaxr, feature["Qmaxr"], "flt2")

            common.setText(self.ui.P_discharg, feature["P_discharg"], "flt2")
            common.setText(self.ui.O_discharg, feature["O_discharg"], "flt2")
            common.setText(self.ui.L_discharg, feature["L_discharg"], "flt2")
            common.setText(self.ui.D_discharg, feature["D_discharg"], "flt2")

            common.setText(self.ui.z_BlockID, feature["BlockID"], "int")
            common.setText(self.ui.z_BlockName, feature["BlockName"], "str")
            common.setText(self.ui.z_BlockQmax, feature["BlockQmax"], "flt2")
            common.setText(self.ui.z_BlockBA, feature["BlockBA"], "flt1")
            common.setText(self.ui.z_Road, feature["Road"], "flt1")
            self.sansho = feature["ObservedP"]

            self.ui.grpHint.setVisible(False)
            self.ui.grpLink.setVisible(False)
            self.ui.grpZone.setVisible(True)
            self.ui.btnPdf.setVisible(True)
            self.ui.btnClipZone.setVisible(True)

            self.mode = "ZONE"

        elif layer.name() == const.LINK_LYR_NAME:
            self.line_pr.addFeatures( [ feature ] )

            common.setText(self.ui.l_LinkID, feature["LinkID"], "int")
            common.setText(self.ui.l_IC, feature["IC"], "int")
            common.setText(self.ui.l_UCCost, feature["UCCost"], "flt1")
            common.setText(self.ui.l_BlockID, feature["BlockID"], "int")
            common.setText(self.ui.l_BlockName, feature["BlockName"], "str")

            self.ui.grpHint.setVisible(False)
            self.ui.grpLink.setVisible(True)
            self.ui.grpZone.setVisible(False)
            self.ui.btnPdf.setVisible(True)
            self.ui.btnClipZone.setVisible(True)

            self.mode = "LINK"

        self.point_vl.updateExtents()
        self.point_vl.commitChanges()
        self.point_vl.triggerRepaint()

        self.line_vl.updateExtents()
        self.line_vl.commitChanges()
        self.line_vl.triggerRepaint()

    def erase_line(self):
        #テンポラリーレイヤー削除
        common.deleteToolLayer()

    def clip_zone(self):
        if self.mode == "ZONE":
            str = u"セグメントID\t" + self.ui.z_SegmentID.text() + "\n"
            str += u"標高\t" + self.ui.z_Elevation.text() + "\tm" + "\n"
            str += u"流域面積\t" + self.ui.z_AccumWSA.text() + "\tkm2" + "\n"
            str += u"使用可能水量\t" + self.ui.z_Qmaxr.text() + "\tm3/s"  + "\n"

            str += u"豊水流量\t" + self.ui.P_discharg.text() + "\tm3/s"  + "\n"
            str += u"平水流量\t" + self.ui.O_discharg.text() + "\tm3/s"  + "\n"
            str += u"低水流量\t" + self.ui.L_discharg.text() + "\tm3/s"  + "\n"
            str += u"渇水流量\t" + self.ui.D_discharg.text() + "\tm3/s"  + "\n"

            str += u"代表観測所ID\t" + self.ui.z_BlockID.text() + "\n"
            str += u"代表観測所名称\t" + self.ui.z_BlockName.text() + "\n"
            str += u"代表観測所の使用可能水量\t" + self.ui.z_BlockQmax.text() + "\tm3/s"  + "\n"
            str += u"代表観測所の流域面積\t" + self.ui.z_BlockBA.text() + "\tkm2" + "\n"
            str += u"幅員3m以上の道路までの距離\t" + self.ui.z_Road.text() + "\tm" + "\n"

            clipboard = QApplication.clipboard()
            clipboard.setText(str)

        elif self.mode == "LINK":
            str = u"仮想発電所ID\t" + self.ui.l_LinkID.text() + "\n"
            str += u"設備容量\t" + self.ui.l_IC.text() + "\tkW" + "\n"
            str += u"建設単価\t" + self.ui.l_UCCost.text() + u"\t千円/kW" + "\n"
            str += u"代表観測所ID\t" + self.ui.l_BlockID.text() + "\n"
            str += u"代表観測所名称\t" + self.ui.l_BlockName.text() + "\n"

            clipboard = QApplication.clipboard()
            clipboard.setText(str)

    def print_map(self):

        try:

            QApplication.setOverrideCursor(Qt.WaitCursor)

            filename = "print_" + datetime.now().strftime('%Y%m%d_%H%M%S') + ".pdf"
            filename = os.path.dirname(__file__) + "/temp/" + filename
            try:
                for fl in glob.glob(os.path.dirname(__file__) + "/temp/*.pdf"):
                    os.remove(fl)
            except:
                pass

            mapRenderer = self.canvas.mapRenderer()
            c = QgsComposition(mapRenderer)
            c.setPlotStyle(QgsComposition.Print)

            #A4縦
            c.setPaperSize(210, 297)

            #フォント作成
            if os.name == "nt":
                font = QFont("MS PGothic", 12, QFont.Normal)
                font_num = QFont("MS Gothic", 12, QFont.Normal)
                font_sub = QFont("MS Gothic", 16, QFont.Normal)
            else:
                font = QFont("Hiragino Kaku Gothic Pro", 12, QFont.Normal)
                font_num = QFont("Courier", 10, QFont.Normal)
                font_sub = QFont("Hiragino Kaku Gothic Pro", 14, QFont.Normal)

            if self.mode=="LINK":
                #タイトル表示
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/title.png")
                pict.setSceneRect(QRectF(13, 13, 123.48, 17.99))
                c.addComposerPicture(pict)

                #マップ
                map = QgsComposerMap(c, 13 ,37, 180, 138)
                map.mDrawCanvasItems = True
                map.setFrameEnabled(True)
                c.addItem(map)

                #方角
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/direct.png")
                pict.setSceneRect(QRectF(15, 162, 9.17, 10.05))
                c.addComposerPicture(pict)

                #スケール
                item = QgsComposerScaleBar(c)
                item.setStyle('Single Box')
                item.setComposerMap(map)
                item.applyDefaultSize()
                item.setItemPosition(25, 160)
                c.addItem(item)

                #凡例
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/legend_link.png")
                pict.setSceneRect(QRectF(162, 143, 29.46, 27.17))
                c.addComposerPicture(pict)

                #情報タイトル
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/link_info.png")
                pict.setSceneRect(QRectF(13, 177, 179.93, 10.94))
                c.addComposerPicture(pict)

                text = QgsComposerLabel(c)
                text.setFont(font_sub)
                text.setText(u"仮想発電所の情報")
                text.setItemPosition(15, 178.5)
                text.adjustSizeToText()
                c.addItem(text)

                #仮想発電所ID
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"仮想発電所ID")
                text.setItemPosition(13, 195)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.l_LinkID.text(),"str"))
                text.setItemPosition(80, 195)
                text.adjustSizeToText()
                c.addItem(text)

                #仮想発電所の設備容量
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"仮想発電所の設備容量")
                text.setItemPosition(13, 204)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.l_IC.text(),"p_flt1"))
                text.setItemPosition(80, 204)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"kW")
                text.setItemPosition(102, 204)
                text.adjustSizeToText()
                c.addItem(text)

                #建設単価
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"建設単価")
                text.setItemPosition(13, 213)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.l_UCCost.text(),"p_flt1"))
                text.setItemPosition(80, 213)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"千円/kW")
                text.setItemPosition(102, 213)
                text.adjustSizeToText()
                c.addItem(text)

                #代表観測所ID
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"代表観測所ID")
                text.setItemPosition(13, 222)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.l_BlockID.text(),"str"))
                text.setItemPosition(80, 222)
                text.adjustSizeToText()
                c.addItem(text)

                #代表観測所名称
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"代表観測所名称")
                text.setItemPosition(13, 231)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(common.textFormat(self.ui.l_BlockName.text(),"str"))
                text.setItemPosition(80, 231)
                text.adjustSizeToText()
                c.addItem(text)

                #流況曲線
                filepath = os.path.dirname(__file__) + u"/ryukyozu/流況曲線_"+self.ui.l_BlockID.text()+".png"
                if os.path.exists(filepath):
                    pict = QgsComposerPicture(c)
                    pict.setPicturePath(filepath)
                    pict.setSceneRect(QRectF(120, 195, 71.12, 47.41))
                    pict.setFrameEnabled(True)
                    c.addComposerPicture(pict)

                    text = QgsComposerLabel(c)
                    text.setFont(font)
                    text.setText(u"代表観測所の流況曲線")
                    text.setItemPosition(133, 243)
                    text.adjustSizeToText()
                    c.addItem(text)

                #メモ
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/memo.png")
                pict.setSceneRect(QRectF(13, 255, 180.98, 30.16))
                c.addComposerPicture(pict)

            elif self.mode=="ZONE":
                #タイトル表示
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/title_zone.png")
                pict.setSceneRect(QRectF(13, 13, 123.48, 17.99))
                c.addComposerPicture(pict)

                #マップ
                composerMap = QgsComposerMap(c, 13 ,35, 180, 115)
                composerMap.mDrawCanvasItems = True
                composerMap.setFrameEnabled(True)
                c.addItem(composerMap)

                #方角
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/direct.png")
                pict.setSceneRect(QRectF(15, 137, 9.17, 10.05))
                c.addComposerPicture(pict)

                #スケール
                item = QgsComposerScaleBar(c)
                item.setStyle('Single Box')
                item.setComposerMap(composerMap)
                item.applyDefaultSize()
                item.setItemPosition(25, 135)
                c.addItem(item)

                #情報タイトル
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/zone_info.png")
                pict.setSceneRect(QRectF(13, 153, 179.93, 10.94))
                c.addComposerPicture(pict)

                text = QgsComposerLabel(c)
                text.setFont(font_sub)
                text.setText(u"水路100mセグメントの情報")
                text.setItemPosition(15, 154.5)
                text.adjustSizeToText()
                c.addItem(text)

                #セグメントID
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"セグメントID")
                text.setItemPosition(13, 168)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_SegmentID.text(),"str"))
                text.setItemPosition(80, 168)
                text.adjustSizeToText()
                c.addItem(text)

                #標高
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"標高")
                text.setItemPosition(13, 177)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_Elevation.text(),"p_intComma"))
                text.setItemPosition(80, 177)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"m")
                text.setItemPosition(102, 177)
                text.adjustSizeToText()
                c.addItem(text)

                #流域面積
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"流域面積")
                text.setItemPosition(13, 186)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_AccumWSA.text(),"p_flt1"))
                text.setItemPosition(80, 186)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"km2")
                text.setItemPosition(102, 186)
                text.adjustSizeToText()
                c.addItem(text)

                #使用可能水量
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"使用可能水量")
                text.setItemPosition(13, 195)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_Qmaxr.text(),"p_flt2"))
                text.setItemPosition(80, 195)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"m3/s")
                text.setItemPosition(102, 195)
                text.adjustSizeToText()
                c.addItem(text)

                #代表観測所ID
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"代表観測所ID")
                text.setItemPosition(13, 204)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_BlockID.text(),"str"))
                text.setItemPosition(80, 204)
                text.adjustSizeToText()
                c.addItem(text)

                #代表観測所名称
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"代表観測所名称")
                text.setItemPosition(13, 213)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(common.textFormat(self.ui.z_BlockName.text(),"str"))
                text.setItemPosition(80, 213)
                text.adjustSizeToText()
                c.addItem(text)

                #代表観測所の流域面積
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"代表観測所の流域面積")
                text.setItemPosition(13, 222)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_BlockBA.text(),"p_flt1"))
                text.setItemPosition(80, 222)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"km2")
                text.setItemPosition(102, 222)
                text.adjustSizeToText()
                c.addItem(text)

                #幅員3m以上の道路までの距離
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"幅員3m以上の道路までの距離")
                text.setItemPosition(13, 231)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font_num)
                text.setText(common.textFormat(self.ui.z_Road.text(),"p_flt1"))
                text.setItemPosition(80, 231)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"m")
                text.setItemPosition(102, 231)
                text.adjustSizeToText()
                c.addItem(text)

                #参照した日流量データ
                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(u"参照した日流量データ")
                text.setItemPosition(13, 240)
                text.adjustSizeToText()
                c.addItem(text)

                text = QgsComposerLabel(c)
                text.setFont(font)
                text.setText(common.textFormat(self.sansho,"str"))
                text.setItemPosition(80, 240)
                text.adjustSizeToText()
                c.addItem(text)

                #流況曲線
                filepath = os.path.dirname(__file__) + u"/ryukyozu/流況曲線_"+self.ui.z_BlockID.text()+".png"
                if os.path.exists(filepath):
                    pict = QgsComposerPicture(c)
                    pict.setPicturePath(filepath)
                    pict.setSceneRect(QRectF(120, 168, 71.12, 47.41))
                    pict.setFrameEnabled(True)
                    c.addComposerPicture(pict)

                    text = QgsComposerLabel(c)
                    text.setFont(font)
                    text.setText(u"代表観測所の流況曲線")
                    text.setItemPosition(133, 216)
                    text.adjustSizeToText()
                    c.addItem(text)

                #メモ
                pict = QgsComposerPicture(c)
                pict.setPicturePath(os.path.dirname(__file__) + "/print/memo.png")
                pict.setSceneRect(QRectF(13, 255, 180.98, 30.16))
                c.addComposerPicture(pict)

            else:
                return

            printer = QPrinter()
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(filename)
            printer.setPaperSize(QSizeF(c.paperWidth(), c.paperHeight()), QPrinter.Millimeter)
            printer.setFullPage(True)
            printer.setColorMode(QPrinter.Color)
            printer.setResolution(c.printResolution())

            pdfPainter = QPainter(printer)
            paperRectMM = printer.pageRect(QPrinter.Millimeter)
            paperRectPixel = printer.pageRect(QPrinter.DevicePixel)
            c.render(pdfPainter, paperRectPixel, paperRectMM)
            pdfPainter.end()

            if os.name == "nt":
                os.system('start '+filename)
            else:
                os.system('open '+filename)

        except:
            pass

        finally:
            #マウスカーソル戻す
            QApplication.restoreOverrideCursor()
            QApplication.restoreOverrideCursor()    #2回呼び出す必要
