# -*- coding: utf-8 -*-
"""
/***************************************************************************
 FacilityLocation
                                 A QGIS plugin
 Dati un insieme di layer vettoriali di punti di clienti e di zone, e un intero k determina le k zone ottimali in cui costruire le facility.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-01-12
        git sha              : $Format:%H$
        copyright            : (C) 2021 by Peppe&Berni
        email                : peppe&berni@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction,QFileDialog
from qgis.core import QgsProject,Qgis,QgsWkbTypes


# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .FacilityLocation_dialog import FacilityLocationDialog
import os.path
from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout,QFormLayout, QGroupBox,
        QMenu, QPushButton, QRadioButton, QVBoxLayout,QLabel, QWidget, QComboBox,QMessageBox)
from .location_allocation import *

class FacilityLocation:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'FacilityLocation_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Facility Location')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('FacilityLocation', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/FacilityLocation/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Facility Location'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Facility Location'),
                action)
            self.iface.removeToolBarIcon(action)

    def currentFieldCombo(self,layer):
        """
           A partire dal layer selezionato,crea una lista con tutti gli attributi del layer   
    
           Parameter:
           index_layer(int):intero che ci permette di risalire al layer selezionato

           Return:
           (String[]) una lista con tutti gli attributi del layer
           
        """
        fields = [field.name() for field in ((layer.layer()).fields())]  
        fields.insert(0, "")
        return fields


    def window():
        app = QApplication(sys.argv)
        win = QWidget()
        button1 = QPushButton(win)
        button1.setText("Show dialog!")
        button1.move(50,50)
        button1.clicked.connect(showDialog)
        win.setWindowTitle("Click button")
        win.show()
        sys.exit(app.exec_())

    def showDialog():
        msgBox = QMessageBox()
        msgBox.setIcon(QMessageBox.Information)
        msgBox.setText("Message box pop up window")
        msgBox.setWindowTitle("QMessageBox Example")
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgBox.buttonClicked.connect(msgButtonClick)

        returnValue = msgBox.exec()
        if returnValue == QMessageBox.Ok:
            print('OK clicked')
    
    def msgButtonClick(i):
        print("Button clicked is:",i.text())

    
    def popup_invalid_input(self,msg):
        self.dlg.close()
        reply = QMessageBox.question(self.iface.mainWindow(), 'Error', msg, QMessageBox.Ok)
        if reply == QMessageBox.Ok:
            self.run()

    def operation_with_street(self,layers_punti_name,layers_punti,layers_strade_name,layers_strade,checkboxes_client_tab2,comboBoxes_client_tab2,comboBoxesw_client_tab2,checkboxes_zone_tab2,comboBoxes_zone_tab2,checkboxes_street_tab2):

        client_param_tab2={} #dizionario dei clienti tab2, { key = nome_layer, value = { 'key' = chiave layer, 'weight' = peso cliente} } 
        zone_param_tab2={}   #dizionario delle zone tab2,  { key = nome_layer, value = chiave layer }

        zone_layers_tab2 = []
        client_layers_tab2 = []


        flag_number_location_tab2 = True

        number_facilities_tab2 = self.dlg.lineEdit_27.text()

        if number_facilities_tab2 != "": 
            flag_number_location_tab2 = False
            number_facilities_tab2= int(number_facilities_tab2)

                
        name_layer_facilities_tab2 = self.dlg.lineEdit_40.text()

        name_client_to_zone_paths_tab2 = self.dlg.lineEdit_52.text()

        key_client_not_selected=False
        
        for j in range(len(layers_punti_name)):
            if checkboxes_client_tab2[layers_punti_name[j]].isChecked():
                param_layer_client_tab2 = {}
                fields_layer=self.currentFieldCombo(layers_punti[j])
                indice_key=comboBoxes_client_tab2[layers_punti_name[j]].currentIndex()
                indice_weight=comboBoxesw_client_tab2[layers_punti_name[j]].currentIndex()
                param_layer_client_tab2['key']=fields_layer[indice_key]
                if(param_layer_client_tab2['key']==""):
                    key_client_not_selected=True
                weight = fields_layer[indice_weight]
                param_layer_client_tab2['weight']=weight
                client_param_tab2[layers_punti_name[j]] = param_layer_client_tab2
                client_layers_tab2.append(layers_punti[j].layer())


        key_zone_not_selected=False
        
        for j in range(len(layers_punti_name)):
            if checkboxes_zone_tab2[layers_punti_name[j]].isChecked():
                fields_layer1=self.currentFieldCombo(layers_punti[j])
                indice_key1=comboBoxes_zone_tab2[layers_punti_name[j]].currentIndex()
                zone_param_tab2[layers_punti_name[j]]=fields_layer1[indice_key1]
                if(zone_param_tab2[layers_punti_name[j]]==""):
                    key_zone_not_selected=True
                zone_layers_tab2.append(layers_punti[j].layer())

        street_layer = []
         
        
        for j in range(len(layers_strade_name)):
            if checkboxes_street_tab2[layers_strade_name[j]].isChecked():
                #street_layer = layer_name[j]
                street_layer.append(layers_strade[j].layer())

      
        path_not_find=False
        
        if(len(client_layers_tab2) == 0):
            self.popup_invalid_input("Select at least one client layer")
        elif(key_client_not_selected):
            self.popup_invalid_input("Select keys for all selected client layers")
        elif(len(zone_layers_tab2) == 0):
            self.popup_invalid_input("Select at least one zone layer")
        elif(key_zone_not_selected):
            self.popup_invalid_input("Select keys for all selected zone layers")
        elif(len(street_layer) != 1):
            self.popup_invalid_input("Select exactly one street!!")
        elif(flag_number_location_tab2):
            self.popup_invalid_input("Specify the number of facility")
        else:
            try:
                clients_dict = get_all_dict_clients(client_layers_tab2,client_param_tab2)
            except (ValueError) as e:
                self.popup_invalid_input(str(e))
                return
            
            zones_dict = get_all_dict_zones(zone_layers_tab2, zone_param_tab2)
            streets = all_street(street_layer[0])

            try:
                OD_lenght, OD_path = OD_matrix_street_distance_A_star(clients_dict,zones_dict,streets)

                dict_facility = locate_allocate(clients_dict,zones_dict,number_facilities_tab2,OD_lenght)
    
                dict_campi_facility = {
                     "id" : QVariant.Int,
                     "chiave + nome layer" :  QVariant.String,
                }
                output_layer_feature(dict_campi_facility,dict_facility,nome_layer=name_layer_facilities_tab2, load_in_project = True)
                output_street_from_client_to_zone(dict_facility, clients_dict, OD_path,nome_layer=name_client_to_zone_paths_tab2,load_in_project = True)
       
                self.dlg.close()

            except (nx.NetworkXNoPath, nx.exception.NetworkXError,nx.exception.NodeNotFound):
                self.popup_invalid_input("Path not find")


    def operation_without_street(self,layers_punti_name,layers_punti,checkboxes_client_tab1,comboBoxes_client_tab1,comboBoxesw_client_tab1,checkboxes_zone_tab1,comboBoxes_zone_tab1):
        client_param_tab1={} #dizionario dei clienti tab1, { key = nome_layer, value = { 'key' = chiave layer, 'weight' = peso cliente} } 
        zone_param_tab1={}   #dizionario delle zone tab1,  { key = nome_layer, value = chiave layer }

        zone_layers_tab1 = []
        client_layers_tab1 = []


        flag_number_location_tab1 = True
            
        number_facilities = self.dlg.lineEdit.text()
        if number_facilities != "": 
            flag_number_location_tab1 = False
            number_facilities = int(number_facilities)



        name_layer_facilities_tab1 = self.dlg.lineEdit_3.text()
        name_client_to_zone_paths_tab1 = self.dlg.lineEdit_4.text()

        key_client_not_selected=False
        
        for j in range(len(layers_punti_name)):
            if checkboxes_client_tab1[layers_punti_name[j]].isChecked():
                param_layer_client_tab1 = {}
                fields_layer=self.currentFieldCombo(layers_punti[j])
                indice_key=comboBoxes_client_tab1[layers_punti_name[j]].currentIndex()
                indice_weight=comboBoxesw_client_tab1[layers_punti_name[j]].currentIndex()
                param_layer_client_tab1['key']=fields_layer[indice_key]
                if(param_layer_client_tab1['key']==""):
                    key_client_not_selected=True
                weight = fields_layer[indice_weight]
                param_layer_client_tab1['weight']=weight
                client_param_tab1[layers_punti_name[j]] = param_layer_client_tab1
                client_layers_tab1.append(layers_punti[j].layer())

        key_zone_not_selected=False
       
        for j in range(len(layers_punti_name)):
            if checkboxes_zone_tab1[layers_punti_name[j]].isChecked():
                fields_layer1=self.currentFieldCombo(layers_punti[j])
                indice_key1=comboBoxes_zone_tab1[layers_punti_name[j]].currentIndex()            
                zone_param_tab1[layers_punti_name[j]]=fields_layer1[indice_key1]
                if(zone_param_tab1[layers_punti_name[j]]==""):
                    key_zone_not_selected=True
                zone_layers_tab1.append(layers_punti[j].layer())


     
        
        if(len(client_layers_tab1) == 0):
            self.popup_invalid_input("Select at least one client layer")
        elif(key_client_not_selected):
            self.popup_invalid_input("Select keys for all selected client layers")
        elif(len(zone_layers_tab1) == 0):
            self.popup_invalid_input("Select at least one zone layer")
        elif(key_zone_not_selected):
            self.popup_invalid_input("Select keys for all selected zone layers")
        elif(flag_number_location_tab1):
            self.popup_invalid_input("Specify the number of facility")
        else:

            try:
                clients_dict = get_all_dict_clients(client_layers_tab1,client_param_tab1)
            except (ValueError) as e:
                self.popup_invalid_input(str(e))
                return

            zones_dict = get_all_dict_zones(zone_layers_tab1, zone_param_tab1)

            OD_matrix = OD_matrix_line_distance(clients_dict,zones_dict)
            dict_facility = locate_allocate(clients_dict,zones_dict,number_facilities,OD_matrix)

            dict_campi_facility = {
                    "id" : QVariant.Int,
                    "chiave + nome layer" :  QVariant.String,
            }
        
            output_layer_feature(dict_campi_facility,dict_facility,nome_layer=name_layer_facilities_tab1, load_in_project = True)
            output_line_feature(dict_facility,clients_dict,nome_layer=name_client_to_zone_paths_tab1,load_in_project = True)
        
            self.dlg.close()

    def line_referencing_tab3(self,layers_punti_name,layers_punti,layers_strade_name,layers_strade,checkboxes_dot,checkboxes_street_lr):
        name_con_seg_layer_lr = self.dlg.lineEdit_5.text() 

        street_layer = []

        name_street_seg_layer_lr = self.dlg.lineEdit_6.text()
 
        dot_layers = []
        
        for j in range(len(layers_punti_name)):
            if checkboxes_dot[layers_punti_name[j]].isChecked():
                dot_layers.append(layers_punti[j].layer())
                

       
        for j in range(len(layers_strade_name)):
            if checkboxes_street_lr[layers_strade_name[j]].isChecked():
                street_layer.append(layers_strade[j].layer())

       
        if(len(dot_layers) == 0):
            self.popup_invalid_input("Select at least one dot layer")
        elif(len(street_layer) != 1):
            self.popup_invalid_input("Select only one street layer!!")
        else:
            dots_list = get_all_dot_list(dot_layers)
            streets = all_street(street_layer[0])
            line_referencing_segment = line_referencing(dots_list,streets)
            line_referencing_segment_layer = output_line_referencing(line_referencing_segment,nome_layer = name_con_seg_layer_lr,load_in_project=True)
            output_street_with_line_referencing(streets,nome_layer = name_street_seg_layer_lr, load_in_project=True)
            self.dlg.close()

    def setup_clienti(self,layers,layer_name,checkboxes_client,comboboxes_client,comboboxes_weight,groupboxes_client,gridlayout_client,scrollLayout_client):
       
        for i in range(len(layer_name)):
            checkboxes_client[layer_name[i]]=QCheckBox(layer_name[i])
            comboboxes_client[layer_name[i]]=QComboBox()
            comboboxes_weight[layer_name[i]]=QComboBox()
            groupboxes_client.append(QGroupBox())
            gridlayout_client.append(QGridLayout())
            gridlayout_client[i].addWidget(checkboxes_client[layer_name[i]],0,0)
            formLayout1_client_tab1=QFormLayout()
            formLayout2_client_tab1=QFormLayout()
            groupbox1_client_tab1=QGroupBox()
            groupbox2_client_tab1=QGroupBox()
            formLayout1_client_tab1.addRow(QLabel("Key"),comboboxes_client[layer_name[i]])
            formLayout2_client_tab1.addRow(QLabel("Weight"),comboboxes_weight[layer_name[i]])
            groupbox1_client_tab1.setLayout(formLayout1_client_tab1)
            groupbox2_client_tab1.setLayout(formLayout2_client_tab1)
            gridlayout_client[i].addWidget(groupbox1_client_tab1,0,1)
            gridlayout_client[i].addWidget(groupbox2_client_tab1,0,2)
            groupboxes_client[i].setLayout(gridlayout_client[i])
            scrollLayout_client.addWidget(groupboxes_client[i])
            comboboxes_client[layer_name[i]].clear()
            comboboxes_client[layer_name[i]].addItems(self.currentFieldCombo(layers[i]))
            comboboxes_weight[layer_name[i]].clear()
            comboboxes_weight[layer_name[i]].addItems(self.currentFieldCombo(layers[i]))

    def setup_zone(self,layers,layer_name,checkboxes_zone,comboboxes_zone,groupboxes_zone,gridlayouts_zone,scrollLayout_zone):
        for i in range(len(layer_name)):
            checkboxes_zone[layer_name[i]]=QCheckBox(layer_name[i])
            comboboxes_zone[layer_name[i]]=QComboBox()
            groupboxes_zone.append(QGroupBox())
            gridlayouts_zone.append(QGridLayout())
            gridlayouts_zone[i].addWidget(checkboxes_zone[layer_name[i]],0,0)
            
            formLayout3_zone_tab2=QFormLayout()
            groupbox3_zone_tab2=QGroupBox()
            formLayout3_zone_tab2.addRow(QLabel("Key"),comboboxes_zone[layer_name[i]])
            groupbox3_zone_tab2.setLayout(formLayout3_zone_tab2)

            gridlayouts_zone[i].addWidget(groupbox3_zone_tab2,0,1)
            groupboxes_zone[i].setLayout(gridlayouts_zone[i])
            scrollLayout_zone.addWidget(groupboxes_zone[i])
            comboboxes_zone[layer_name[i]].clear()
            comboboxes_zone[layer_name[i]].addItems(self.currentFieldCombo(layers[i]))


    def setup_strade(self,layers,layer_name,checkboxes_street,comboboxes_street,groupboxes_street,gridlayout_street,scrollLayout_street):
        for i in range(len(layer_name)):
            checkboxes_street[layer_name[i]]=QCheckBox(layer_name[i])
            comboboxes_street[layer_name[i]]=QComboBox()
            groupboxes_street.append(QGroupBox())
            gridlayout_street.append(QGridLayout())
            gridlayout_street[i].addWidget(checkboxes_street[layer_name[i]],0,0)
            groupboxes_street[i].setLayout(gridlayout_street[i])
            scrollLayout_street.addWidget(groupboxes_street[i])
            comboboxes_street[layer_name[i]].clear()
            comboboxes_street[layer_name[i]].addItems(self.currentFieldCombo(layers[i]))


    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        self.dlg = FacilityLocationDialog()
        
        layers = QgsProject.instance().layerTreeRoot().children()
        
        layer_name=[layer.name() for layer in layers]

        layers_punti = []
        layers_punti_name = []

        layers_strade = []
        layers_strade_name = []


        for i in range(len(layer_name)):
            layer_type=layers[i].layer().geometryType()
            if(layer_type==0):
                layers_punti.append(layers[i])
                layers_punti_name.append(layer_name[i])
            elif(layer_type==1):
                layers_strade.append(layers[i])
                layers_strade_name.append(layer_name[i])


        # CLIENT TAB1
        checkboxes_client_tab1={}
        comboBoxes_client_tab1={}
        comboBoxesw_client_tab1={}
        groupboxes_client_tab1=[]
        gridlayouts_client_tab1=[]

        scrollContent_client_tab1 = QWidget(self.dlg.scrollArea_client_tab1)
        scrollLayout_client_tab1 = QVBoxLayout(scrollContent_client_tab1)
        self.dlg.scrollArea_client_tab1.setWidget(scrollContent_client_tab1)

        
        # ZONE TAB1
        checkboxes_zone_tab1={}
        comboBoxes_zone_tab1={}
        groupboxes_zone_tab1=[]
        gridlayouts_zone_tab1=[]

        scrollContent_zone_tab1 = QWidget(self.dlg.scrollArea_zone_tab1)
        scrollLayout_zone_tab1 = QVBoxLayout(scrollContent_zone_tab1)
        self.dlg.scrollArea_zone_tab1.setWidget(scrollContent_zone_tab1)

        # CLIENT TAB2
        checkboxes_client_tab2={}
        comboBoxes_client_tab2={}
        comboBoxesw_client_tab2={}
        groupboxes_client_tab2=[]
        gridlayouts_client_tab2=[]

        scrollContent_client_tab2 = QWidget(self.dlg.scrollArea_client_tab2)
        scrollLayout_client_tab2 = QVBoxLayout(scrollContent_client_tab2)
        self.dlg.scrollArea_client_tab2.setWidget(scrollContent_client_tab2)

        # ZONE TAB2
        checkboxes_zone_tab2={}
        comboBoxes_zone_tab2={}
        groupboxes_zone_tab2=[]
        gridlayouts_zone_tab2=[]

        scrollContent_zone_tab2 = QWidget(self.dlg.scrollArea_zone_tab2)
        scrollLayout_zone_tab2 = QVBoxLayout(scrollContent_zone_tab2)
        self.dlg.scrollArea_zone_tab2.setWidget(scrollContent_zone_tab2)
        
        # STREET TAB2
        checkboxes_street_tab2={}
        comboBoxes_street_tab2={}
        groupboxes_street_tab2=[]
        gridlayouts_street_tab2=[]
        
        scrollContent_street_tab2 = QWidget(self.dlg.scrollArea_street_tab2)
        scrollLayout_street_tab2= QVBoxLayout(scrollContent_street_tab2)
        self.dlg.scrollArea_street_tab2.setWidget(scrollContent_street_tab2)


        #DOT LINE REFERENCING GUI
        checkboxes_dot={}
        comboBoxes_dot={}
        groupboxes_dot=[]
        gridlayouts_dot=[]
        
        scrollContent_dot = QWidget(self.dlg.scrollArea_dot)
        scrollLayout_dot= QVBoxLayout(scrollContent_dot)
        self.dlg.scrollArea_dot.setWidget(scrollContent_dot)

        #STREET LINE REFERENCING GUI
        checkboxes_street_lr={}
        comboBoxes_street_lr={}
        groupboxes_street_lr=[]
        gridlayouts_street_lr=[]
        
        scrollContent_street_lr = QWidget(self.dlg.scrollArea_street_lr)
        scrollLayout_street_lr= QVBoxLayout(scrollContent_street_lr)
        self.dlg.scrollArea_street_lr.setWidget(scrollContent_street_lr)

        #setup tab1
        self.setup_clienti(layers_punti,layers_punti_name,checkboxes_client_tab1,comboBoxes_client_tab1,comboBoxesw_client_tab1,groupboxes_client_tab1,gridlayouts_client_tab1,scrollLayout_client_tab1)      
        self.setup_zone(layers_punti, layers_punti_name, checkboxes_zone_tab1,comboBoxes_zone_tab1,groupboxes_zone_tab1,gridlayouts_zone_tab1,scrollLayout_zone_tab1)
        button_senza_strade = self.dlg.pushButton_senza_strade
        button_senza_strade.clicked.connect(lambda:self.operation_without_street(layers_punti_name,layers_punti,checkboxes_client_tab1,comboBoxes_client_tab1,comboBoxesw_client_tab1,checkboxes_zone_tab1,comboBoxes_zone_tab1))

        #setup tab2
        self.setup_clienti(layers_punti,layers_punti_name,checkboxes_client_tab2,comboBoxes_client_tab2,comboBoxesw_client_tab2,groupboxes_client_tab2,gridlayouts_client_tab2,scrollLayout_client_tab2)
        self.setup_zone(layers_punti, layers_punti_name, checkboxes_zone_tab2,comboBoxes_zone_tab2,groupboxes_zone_tab2,gridlayouts_zone_tab2,scrollLayout_zone_tab2)        
        self.setup_strade(layers_strade,layers_strade_name,checkboxes_street_tab2,comboBoxes_street_tab2,groupboxes_street_tab2,gridlayouts_street_tab2,scrollLayout_street_tab2)
        button_con_strade = self.dlg.pushButton_con_strade
        button_con_strade.clicked.connect(lambda:self.operation_with_street(layers_punti_name,layers_punti,layers_strade_name,layers_strade,checkboxes_client_tab2,comboBoxes_client_tab2,comboBoxesw_client_tab2,checkboxes_zone_tab2,comboBoxes_zone_tab2,checkboxes_street_tab2)) 


        #setup tab3
        #DOT LINE REFERENCING GUI 
        for i in range(len(layers_punti_name)):
            checkboxes_dot[layers_punti_name[i]]=QCheckBox(layers_punti_name[i])
            comboBoxes_dot[layers_punti_name[i]]=QComboBox()
            groupboxes_dot.append(QGroupBox())
            gridlayouts_dot.append(QGridLayout())
            gridlayouts_dot[i].addWidget(checkboxes_dot[layers_punti_name[i]],0,0)
            groupboxes_dot[i].setLayout(gridlayouts_dot[i])
            scrollLayout_dot.addWidget(groupboxes_dot[i])
            comboBoxes_dot[layers_punti_name[i]].clear()
            comboBoxes_dot[layers_punti_name[i]].addItems(self.currentFieldCombo(layers_punti[i]))

        self.setup_strade(layers_strade,layers_strade_name,checkboxes_street_lr,comboBoxes_street_lr,groupboxes_street_lr,gridlayouts_street_lr,scrollLayout_street_lr)
        button_line_referencing = self.dlg.pushButton_line_referencing
        button_line_referencing.clicked.connect(lambda:self.line_referencing_tab3(layers_punti_name,layers_punti,layers_strade_name,layers_strade,checkboxes_dot,checkboxes_street_lr))


        # show the dialog
        self.dlg.show()
       
        # Run the dialog event loop
        result = self.dlg.exec_()

        if result:
            pass
                
