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

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtSql import *

from manage_net_dialog import ManageNetDialog

class ManageNet():
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.manage_net_dlg = ManageNetDialog()

        self.manage_net_dlg.pushButton_add.clicked.connect(self.create_dimensions)

        self.fill_combo(self.manage_net_dlg.comboBox_first)
        self.fill_combo(self.manage_net_dlg.comboBox_second)

    def fill_combo(self, comboBox):
        layers = self.iface.legendInterface().layers()
        layer_list = []
        for layer in layers:
            layer_list.append(layer.name())
        comboBox.addItems(layer_list)

    def create_dimensions(self):
        registry = QgsMapLayerRegistry.instance()

        selected_first_layer = self.manage_net_dlg.comboBox_first.currentText()
        selected_second_layer = self.manage_net_dlg.comboBox_second.currentText()

        p_lyr = registry.mapLayersByName(selected_first_layer)[0]
        l_lyr = registry.mapLayersByName(selected_second_layer)[0]

        epsg = p_lyr.crs().postgisSrid()
        uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer""&field=distance:double(20,2)&index=yes"

        dim_layer = QgsVectorLayer(uri, 'dimensions', 'memory')
        registry.addMapLayer(dim_layer)
        prov = dim_layer.dataProvider()

        lines_features = [line_feature for line_feature in l_lyr.getFeatures()]
        points_features = [point_feature for point_feature in p_lyr.getFeatures()]

        feats = []
        for p in points_features:
            if p.geometry() != None:
                minDistPoint = min([l.geometry().closestSegmentWithContext(p.geometry().asPoint()) for l in lines_features if l.geometry() != None])[1]
                feat = QgsFeature()
                feat.setGeometry(QgsGeometry.fromPolyline([p.geometry().asPoint(), minDistPoint]))
                feat.setAttributes([points_features.index(p), feat.geometry().length()])
                feats.append(feat)

        prov.addFeatures(feats)

    def run(self):
        self.manage_net_dlg.show()
        # Run the dialog event loop
        result = self.manage_net_dlg.exec_()
        # See if OK was pressed
        if result:
            pass