# -*- 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 MeasureUi import Ui_Form
from ClickFeature import ClickFeature
import common
import const

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

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

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.btnClear.setIcon(QIcon(":/plugins/HydropowerPotential/icon_clear.png"))

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

        #マップツールの定義
        self.thisMapTool = ClickFeature(self.canvas)
        self.thisMapTool.pointClicked.connect(self.draw_line)
        #self.thisMapTool.deactivated.connect(self.erase_line)
        self.canvas.setMapTool(self.thisMapTool)

        self.ui.btnClear.released.connect(self.clear)

        self.init_form()

    def init_form(self):
        self.ui.grpResult.setVisible(False)
        self.ui.lbHint.setVisible(True)

        #データ初期化
        common.setText(self.ui.sum_Kyori, "", "str")
        common.setText(self.ui.sum_Rakusa, "", "str")
        self.ui.tblResult.setRowCount(0)

        self.previous_pos = ""
        self.prev_ele = 0
        self.row_count = 0
        self.kyori = 0
        self.rakusa = 0

        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.4'})
        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,255'})
        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)

    def draw_line(self, event):

        if self.previous_pos != "":

            #ライン
            fet = QgsFeature()
            new_point = QgsPoint(self.thisMapTool.toMapCoordinates(event.pos()))
            geo = QgsGeometry.fromPolyline([self.previous_pos, new_point])
            fet.setGeometry( geo )

            self.line_pr.addFeatures( [ fet ] )
            self.line_vl.updateExtents()
            self.line_vl.triggerRepaint()

            #ポイント
            fet = QgsFeature()
            new_point = QgsPoint(self.thisMapTool.toMapCoordinates(event.pos()))
            geo = QgsGeometry.fromPoint(new_point)
            fet.setGeometry( geo )

            self.point_pr.addFeatures( [ fet ] )
            self.point_vl.updateExtents()
            self.point_vl.triggerRepaint()

            #距離計算
            this_kyori = common.calcM(self.previous_pos.x(), self.previous_pos.y(), new_point.x(), new_point.y())
            self.kyori += this_kyori
            common.setText(self.ui.sum_Kyori, self.kyori, "flt1")

            #落差計算
            this_rakusa = self.prev_ele - common.getHyoko(self, event.pos())
            self.rakusa += this_rakusa
            common.setText(self.ui.sum_Rakusa, self.rakusa, "int")

            #表に出力
            self.ui.tblResult.setRowCount(self.row_count + 1)

            item = QTableWidgetItem("{:,.1f}".format(this_kyori))
            item.setTextAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
            self.ui.tblResult.setItem(self.row_count,0, item)

            item = QTableWidgetItem("{:,.0f}".format(this_rakusa))
            item.setTextAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
            if this_rakusa < 0 :
                item.setForeground(QtGui.QBrush(QtGui.QColor(255, 0, 0)))
            self.ui.tblResult.setItem(self.row_count,1, item)
            self.row_count += 1

        else:

            #初回のポイント
            fet = QgsFeature()
            geo = QgsGeometry.fromPoint(QgsPoint(self.thisMapTool.toMapCoordinates(event.pos())))
            fet.setGeometry( geo )

            self.point_pr.addFeatures( [ fet ] )
            self.point_vl.updateExtents()
            self.point_vl.triggerRepaint()

            self.ui.grpResult.setVisible(True)
            self.ui.lbHint.setVisible(False)

        self.previous_pos = QgsPoint(self.thisMapTool.toMapCoordinates(event.pos()))
        self.prev_ele = common.getHyoko(self, event.pos())

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

    def clear(self):
        self.init_form()
