# -*- 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 SearchUi import Ui_SearchUi
import common
import const
from Descript import DescriptDialog

# ダイアログクラス
class SearchDialog(QDialog, Ui_SearchUi):
    # 初期化
    def __init__(self, iface, apdockwidget, scrollArea):
        #？ボタンは表示しない
        QDialog.__init__(self, None, QtCore.Qt.WindowTitleHint)

        self.ui = Ui_SearchUi()
        self.ui.setupUi(self)

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

        self.joken()

        #表のタイトル作成
        self.ui.tblLink.setColumnCount(6)
        self.ui.tblLink.setHorizontalHeaderItem(0, QTableWidgetItem(u"仮想発電所ID"))
        self.ui.tblLink.setColumnWidth(0,140)
        self.ui.tblLink.setHorizontalHeaderItem(1, QTableWidgetItem(u"設備容量\n(kW)"))
        self.ui.tblLink.setColumnWidth(1,140)
        self.ui.tblLink.setHorizontalHeaderItem(2, QTableWidgetItem(u"建設単価\n(千円/kW)"))
        self.ui.tblLink.setColumnWidth(2,140)
        self.ui.tblLink.setHorizontalHeaderItem(3, QTableWidgetItem(u"代表観測所ID"))
        self.ui.tblLink.setColumnWidth(3,140)
        self.ui.tblLink.setHorizontalHeaderItem(4, QTableWidgetItem(u"代表観測所名称"))
        self.ui.tblLink.setColumnWidth(4,140)
        self.ui.tblLink.setHorizontalHeaderItem(5, QTableWidgetItem(u"フィーチャーID"))
        self.ui.tblLink.setColumnWidth(5,0)

        self.ui.tblZone.setColumnCount(10)
        self.ui.tblZone.setHorizontalHeaderItem(0, QTableWidgetItem(u"セグメントID"))
        self.ui.tblZone.setColumnWidth(0,150)
        self.ui.tblZone.setHorizontalHeaderItem(1, QTableWidgetItem(u"標高\n(m)"))
        self.ui.tblZone.setColumnWidth(1,150)
        self.ui.tblZone.setHorizontalHeaderItem(2, QTableWidgetItem(u"流域面積\n(km2)"))
        self.ui.tblZone.setColumnWidth(2,150)
        self.ui.tblZone.setHorizontalHeaderItem(3, QTableWidgetItem(u"使用可能水量\n(m3/s)"))
        self.ui.tblZone.setColumnWidth(3,150)
        self.ui.tblZone.setHorizontalHeaderItem(4, QTableWidgetItem(u"代表観測所ID"))
        self.ui.tblZone.setColumnWidth(4,150)
        self.ui.tblZone.setHorizontalHeaderItem(5, QTableWidgetItem(u"代表観測所名称"))
        self.ui.tblZone.setColumnWidth(5,150)
        self.ui.tblZone.setHorizontalHeaderItem(6, QTableWidgetItem(u"代表観測所の\n使用可能水量\n(m3/s)"))
        self.ui.tblZone.setColumnWidth(6,150)
        self.ui.tblZone.setHorizontalHeaderItem(7, QTableWidgetItem(u"代表観測所の\n流域面積\n(km2)"))
        self.ui.tblZone.setColumnWidth(7,150)
        self.ui.tblZone.setHorizontalHeaderItem(8, QTableWidgetItem(u"幅員3m以上の\n道路までの距離\n(m)"))
        self.ui.tblZone.setColumnWidth(8,150)
        self.ui.tblZone.setHorizontalHeaderItem(9, QTableWidgetItem(u"フィーチャーID"))
        self.ui.tblZone.setColumnWidth(9,0)

        #イベント設定
        self.ui.btnSearch1.pressed.connect(self.search_link)
        self.ui.btnSearch3.pressed.connect(self.search_zone)
        self.ui.btnCancel1.pressed.connect(self.calcel)
        self.ui.btnCancel3.pressed.connect(self.calcel)
        self.ui.btnCancel4.pressed.connect(self.calcel)
        self.ui.btnJoken.pressed.connect(self.joken)
        self.ui.tblLink.itemClicked.connect(self.click_link)
        self.ui.tblZone.itemClicked.connect(self.click_zone)

        #右に属性表示を出力
        self.descript_dialog = DescriptDialog(self.iface)
        self.scrollArea.setWidget(self.descript_dialog)
        self.iface.addDockWidget( Qt.RightDockWidgetArea, self.apdockwidget )

    def search_zone(self):
        selected = []

        QApplication.setOverrideCursor(Qt.WaitCursor)

        layer = common.getLayerByName(self.iface, const.ZONE_LYR_NAME)
        features = layer.getFeatures()

        max_row = const.SEARCH_ROWS
        self.ui.tblZone.setRowCount(max_row)
        row = -1

        for feature in features:

            #代表観測所名称
            if self.ui.z_BlockName.text() != "":
                if self.ui.z_BlockName_part.isChecked():
                    if feature['BlockName'].find(self.ui.z_BlockName.text()) == -1:
                        continue
                else:
                    if feature['BlockName'] != self.ui.z_BlockName.text():
                        continue

            #標高
            if self.ui.z_Elevation_from.text() != "" and self.ui.z_Elevation_from.text().replace(",","").isdigit():
                if feature['Elevation'] < float(self.ui.z_Elevation_from.text().replace(",","")):
                    continue
            if self.ui.z_Elevation_to.text() != "" and self.ui.z_Elevation_to.text().replace(",","").isdigit():
                if feature['Elevation'] > float(self.ui.z_Elevation_to.text().replace(",","")):
                    continue

            #流域面積
            if self.ui.z_AccumWSA_from.text() != "" and self.ui.z_AccumWSA_from.text().replace(",","").isdigit():
                if feature['AccumWSA'] < float(self.ui.z_AccumWSA_from.text().replace(",","")):
                    continue
            if self.ui.z_AccumWSA_to.text() != "" and self.ui.z_AccumWSA_to.text().replace(",","").isdigit():
                if feature['AccumWSA'] > float(self.ui.z_AccumWSA_to.text().replace(",","")):
                    continue

            #使用可能水量
            if self.ui.z_Qmaxr_from.text() != "" and self.ui.z_Qmaxr_from.text().replace(",","").isdigit():
                if feature['Qmaxr'] < float(self.ui.z_Qmaxr_from.text().replace(",","")):
                    continue
            if self.ui.z_Qmaxr_to.text() != "" and self.ui.z_Qmaxr_to.text().replace(",","").isdigit():
                if feature['Qmaxr'] > float(self.ui.z_Qmaxr_to.text().replace(",","")):
                    continue

            #代表観測所の使用可能水量
            if self.ui.z_BlockQmax_from.text() != "" and self.ui.z_BlockQmax_from.text().replace(",","").isdigit():
                if feature['BlockQmax'] < float(self.ui.z_BlockQmax_from.text().replace(",","")):
                    continue
            if self.ui.z_BlockQmax_to.text() != "" and self.ui.z_BlockQmax_to.text().replace(",","").isdigit():
                if feature['BlockQmax'] > float(self.ui.z_BlockQmax_to.text().replace(",","")):
                    continue

            #代表観測所の流域面積
            if self.ui.z_BlockBA_from.text() != "" and self.ui.z_BlockBA_from.text().replace(",","").isdigit():
                if feature['BlockBA'] < float(self.ui.z_BlockBA_from.text().replace(",","")):
                    continue
            if self.ui.z_BlockBA_to.text() != "" and self.ui.z_BlockBA_to.text().replace(",","").isdigit():
                if feature['BlockBA'] > float(self.ui.z_BlockBA_to.text().replace(",","")):
                    continue

            #幅員3m以上の道路までの距離
            if self.ui.z_Road_from.text() != "" and self.ui.z_Road_from.text().replace(",","").isdigit():
                if feature['Road'] < float(self.ui.z_Road_from.text().replace(",","")):
                    continue
            if self.ui.z_Road_to.text() != "" and self.ui.z_Road_to.text().replace(",","").isdigit():
                if feature['Road'] > float(self.ui.z_Road_to.text().replace(",","")):
                    continue

            #検索結果の表示
            selected.append(feature.id())
            row += 1
            if row > max_row:
                max_row += const.SEARCH_ROWS
                self.ui.tblZone.setRowCount(max_row)

            self.ui.tblZone.setItem(row,0, QTableWidgetItem(common.textFormat(feature["SegmentID"], "flt0")))

            item = QTableWidgetItem(common.textFormat(feature["Elevation"], "flt0"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,1, item)

            item = QTableWidgetItem(common.textFormat(feature["AccumWSA"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,2, item)

            item = QTableWidgetItem(common.textFormat(feature["Qmaxr"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,3, item)

            self.ui.tblZone.setItem(row,4, QTableWidgetItem(common.textFormat(feature["BlockID"], "flt0")))

            self.ui.tblZone.setItem(row,5, QTableWidgetItem(common.textFormat(feature["BlockName"], "str")))

            item = QTableWidgetItem(common.textFormat(feature["BlockQmax"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,6, item)

            item = QTableWidgetItem(common.textFormat(feature["BlockBA"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,7, item)

            item = QTableWidgetItem(common.textFormat(feature["Road"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblZone.setItem(row,8, item)

            self.ui.tblZone.setItem(row,9, QTableWidgetItem(common.textFormat(feature.id(), "int")))

        #表の行数を直す
        self.ui.tblZone.setRowCount(row)

        #レイヤーを選択済みへ
        #layer.selectByIds(selected)
        layer.select(selected)
        self.iface.setActiveLayer(layer)

        #フォーム構成修正
        self.ui.lblResultTitle.setText(u"水路100mセグメントデータ　検索結果")
        self.ui.lblResultTitle.setVisible(True)
        self.ui.tblZone.setVisible(True)
        self.ui.btnJoken.setVisible(True)
        self.ui.btnCancel4.setVisible(True)
        self.ui.tabWidget.setVisible(False)

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

    def search_link(self):
        selected = []

        QApplication.setOverrideCursor(Qt.WaitCursor)

        layer = common.getLayerByName(self.iface, const.LINK_LYR_NAME)
        features = layer.getFeatures()

        max_row = const.SEARCH_ROWS
        self.ui.tblLink.setRowCount(max_row)
        row = -1

        for feature in features:

            #設備容量
            if self.ui.l_IC_from.text() != "" and self.ui.l_IC_from.text().replace(",","").isdigit():
                if feature['IC'] < float(self.ui.l_IC_from.text().replace(",","")):
                    continue
            if self.ui.l_IC_to.text() != "" and self.ui.l_IC_to.text().replace(",","").isdigit():
                if feature['IC'] > float(self.ui.l_IC_to.text().replace(",","")):
                    continue

            #建設単価
            if self.ui.l_UCCost_from.text() != "" and self.ui.l_UCCost_from.text().replace(",","").isdigit():
                if feature['UCCost'] < float(self.ui.l_UCCost_from.text().replace(",","")):
                    continue
            if self.ui.l_UCCost_to.text() != "" and self.ui.l_UCCost_to.text().replace(",","").isdigit():
                if feature['UCCost'] > float(self.ui.l_UCCost_to.text().replace(",","")):
                    continue

            #代表観測所名称
            if self.ui.l_BlockName.text() != "":
                if self.ui.l_BlockName_part.isChecked():
                    if feature['BlockName'].find(self.ui.l_BlockName.text()) == -1:
                        continue
                else:
                    if feature['BlockName'] != self.ui.l_BlockName.text():
                        continue

            #検索結果の表示
            selected.append(feature.id())
            row += 1
            if row > max_row:
                max_row += const.SEARCH_ROWS
                self.ui.tblLink.setRowCount(max_row)

            self.ui.tblLink.setItem(row,0, QTableWidgetItem(common.textFormat(feature["LinkID"], "flt0")))

            item = QTableWidgetItem(common.textFormat(feature["IC"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblLink.setItem(row,1, item)

            item = QTableWidgetItem(common.textFormat(feature["UCCost"], "flt1"))
            item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)
            self.ui.tblLink.setItem(row,2, item)

            self.ui.tblLink.setItem(row,3, QTableWidgetItem(common.textFormat(feature["BlockID"], "flt0")))

            self.ui.tblLink.setItem(row,4, QTableWidgetItem(common.textFormat(feature["BlockName"], "str")))

            self.ui.tblLink.setItem(row,5, QTableWidgetItem(common.textFormat(feature.id(), "int")))


        #表の行数を直す
        self.ui.tblLink.setRowCount(row)

        #レイヤーを選択済みへ
        #layer.selectByIds(selected)
        layer.select(selected)
        self.iface.setActiveLayer(layer)

        #フォーム構成修正
        self.ui.lblResultTitle.setText(u"仮想発電所リンク　検索結果")
        self.ui.lblResultTitle.setVisible(True)
        self.ui.tblLink.setVisible(True)
        self.ui.btnJoken.setVisible(True)
        self.ui.btnCancel4.setVisible(True)
        self.ui.tabWidget.setVisible(False)

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

    def joken(self):
        self.ui.tabWidget.setVisible(True)
        self.ui.lblResultTitle.setVisible(False)
        self.ui.tblLink.setVisible(False)
        self.ui.tblZone.setVisible(False)
        self.ui.btnJoken.setVisible(False)
        self.ui.btnCancel4.setVisible(False)

    def calcel(self):
        self.close()

    def click_link(self, item):
        feature_id = long(self.ui.tblLink.item(item.row(), 5).text())

        layer = common.getLayerByName(self.iface, const.LINK_LYR_NAME)
        feature = common.getFeatureById(layer, feature_id)

        #右ウィンドウに表示
        self.descript_dialog.showAttribute(layer, feature)

        #中心を移動
        self.canvas.zoomToFeatureIds(layer, [feature_id])
        #self.canvas.zoomToPreviousExtent()

    def click_zone(self, item):
        feature_id = long(self.ui.tblZone.item(item.row(), 9).text())

        layer = common.getLayerByName(self.iface, const.ZONE_LYR_NAME)
        feature = common.getFeatureById(layer, feature_id)

        #右ウィンドウに表示
        self.descript_dialog.showAttribute(layer, feature)

        #中心を移動
        self.canvas.zoomToFeatureIds(layer, [feature_id])

