# -*- coding: utf-8 -*-
# ==============================================================================
#
#
# Copyright (c) 2015 IST-SUPSI (www.supsi.ch/ist)
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# ===============================================================================
import csv
import os

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QDialog, QFileDialog, QMessageBox, QSizePolicy, QTableWidgetItem
from qgis.core import QgsDataSourceURI, QgsMapLayerRegistry, QgsProject, QgsVectorLayer
from qgis.gui import QgsMessageBar
from PyQt4 import uic

from pyspatialite import dbapi2 as db
from pyspatialite.dbapi2 import IntegrityError

import freewat.freewat_utils as futils


def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui/ui_createLAKLayer.ui'))


class CreateLAKLayerDialog(QDialog, FORM_CLASS):
    """
    """
    def __init__(self, iface):
        """
        """
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.legend = self.iface.legendInterface()
        self.tree = QgsProject.instance().layerTreeRoot()

        self.suffix = "_lak"
        self.model_name = "t0"
        self.lak_table = "lake_"

        self.backup_idx = []
        self.editing = False
        self.selected = "Table"
        self.bar = QgsMessageBar()
        self.sp_list = None

        self.old_id = None
        self.lak_table_index = None

        self.manage_gui()

        self.model_name = self.lakModel.currentText()

        try:
            pathfile, _ = futils.getModelInfoByName(self.model_name)
            self.path = os.path.join(pathfile, self.model_name + '.sqlite')
        except Exception as e:
            print e

        self.check_if_exists()
        self.get_sp_period()
        self.clear_sp_table()

    def manage_gui(self):
        """
            Init gui
        """
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)

        self.lakQgsMessage.addWidget(self.bar)
        self.lakModel.clear()

        layer_name_list = futils.getVectorLayerNames()
        layer_name_list.sort()

        model_list = futils.getModelsInfoLists(layer_name_list)

        self.lakModel.addItems(model_list[0])

        # Connect button to signal
        self.lakAdd.clicked.connect(self.add_new_lake)
        self.lakCreate.clicked.connect(self.create_lak_layer)
        self.lakDelete.clicked.connect(self.remove_selected)
        self.lakEdit.clicked.connect(self.edit_lak)
        self.lakSaveEdit.clicked.connect(self.save_edit_lake)
        self.lakCancelEdit.clicked.connect(self.clear_edit_lake)
        self.lakUpdateSol.clicked.connect(self.update_solver)

        self.csvButton.clicked.connect(self.load_csv)

        self.lakSaveEdit.setEnabled(False)
        self.lakCancelEdit.setEnabled(False)

        self.csvDelimiter.addItem("Tab", "\t")
        self.csvDelimiter.addItem("Space", " ")
        self.csvDelimiter.addItem("Comma", ",")
        self.csvDelimiter.addItem("Semicolon", ";")

    def update_solver(self):

        theta = self.lakTheta.value()
        nssitr = self.lakNssitr.value()
        sscncr = self.lakSscncr.value()

        sql = "UPDATE lake_{} SET theta=?, nssitr=?, sscncr=?".format(self.model_name)
        params = (theta, nssitr, sscncr)

        self.execute_query(sql, params)

################################################################################
# Edit lak section
################################################################################

    def load_csv(self):

        dialog = QFileDialog()
        filename = dialog.getOpenFileNameAndFilter(self, self.tr("Select input file"), "", "CSV (*.csv)")

        if filename[0] == '':
            return

        with open(filename[0]) as csvfile:

            delimiter = str(self.csvDelimiter.itemData(self.csvDelimiter.currentIndex()))
            reader_elem = csv.DictReader(csvfile, delimiter=delimiter)

            rows = list(reader_elem)

            if len(self.sp_list) != len(rows):
                QMessageBox.warning(self, "Error", "Not enough sp defined")
                # self.clear_sp_table()
                return

            self.lakSpTable.setRowCount(0)

            try:
                for row in rows:
                    #print row
                    idx = self.lakSpTable.rowCount()
                    self.lakSpTable.insertRow(idx)

                    self.lakSpTable.setItem(idx, 0, QTableWidgetItem(str(row['SP'])))
                    self.lakSpTable.setItem(idx, 1, QTableWidgetItem(str(row['PRCPLK'])))
                    self.lakSpTable.setItem(idx, 2, QTableWidgetItem(str(row['EVAPLK'])))
                    self.lakSpTable.setItem(idx, 3, QTableWidgetItem(str(row['RNF'])))
                    self.lakSpTable.setItem(idx, 4, QTableWidgetItem(str(row['WTHDRW'])))

            except KeyError as _:
                QMessageBox.warning(self, "Error parsing CSV",
                                    "Error parsing csv, please check separator")
            except Exception as e:
                QMessageBox.warning(self, "Error parsing CSV", "Error: {}".format(e))

    def clear_edit_lake(self):
        self.lakAdd.setEnabled(True)
        self.lakDelete.setEnabled(True)
        self.lakSaveEdit.setEnabled(False)
        self.lakCancelEdit.setEnabled(False)

        self.clear_sp_table()
        self.clear_lak_params()

    def save_edit_lake(self):
        """
            Save edited lake to db
        """

        lak_params = {
            "lake_id": self.lakId.value(),
            "surfdep": self.lakSurfdep.value(),
            "stages": self.lakStages.value(),
            "ssmn": self.lakSsmn.value(),
            "ssmx": self.lakSsmx.value(),
            "leakance": self.lakLeakance.value(),
            "sp": self.read_sp_data()
        }

        if lak_params['lake_id'] == 0:
            QMessageBox.warning(self, 'lake error', 'lake_id should be different from 0')
            return

        self.update_lak_table(lak_params, self.old_id)
        self.update_lak_table_ui(self.lak_table_index, lak_params)

        self.update_sp_table(lak_params['lake_id'])

        self.lakAdd.setEnabled(True)
        self.lakDelete.setEnabled(True)
        self.lakSaveEdit.setEnabled(False)
        self.lakCancelEdit.setEnabled(False)

        self.clear_sp_table()
        self.clear_lak_params()

    def update_lak_table_ui(self, index, params):
        """
            Update the table in the ui
        """
        self.lakTable.setItem(index, 0, QTableWidgetItem(str(params['lake_id'])))
        self.lakTable.setItem(index, 1, QTableWidgetItem(str(params['surfdep'])))
        self.lakTable.setItem(index, 2, QTableWidgetItem(str(params['stages'])))
        self.lakTable.setItem(index, 3, QTableWidgetItem(str(params['ssmn'])))
        self.lakTable.setItem(index, 4, QTableWidgetItem(str(params['ssmx'])))
        self.lakTable.setItem(index, 5, QTableWidgetItem(str(params['leakance'])))

    def update_sp_table(self, new_id):
        """
            Update modified sp table
        """
        row_count = self.lakSpTable.rowCount()

        for row in range(0, row_count):

            idx_sp = int(self.lakSpTable.item(row, 0).text())
            prc = float(self.lakSpTable.item(row, 1).text())
            evap = float(self.lakSpTable.item(row, 2).text())
            rnf = float(self.lakSpTable.item(row, 3).text())
            whtdrw = float(self.lakSpTable.item(row, 4).text())

            values = [idx_sp, prc, evap, rnf, whtdrw]

            sql = "UPDATE laksp_{} SET lake_id=?, prcplk=?, evaplk=?, rnf=?, wthdrw=? WHERE lake_id=? AND sp=?".format(self.model_name)
            params = (new_id, values[1], values[2], values[3], values[4], self.old_id, values[0])

            try:
                self.execute_query(sql, params)
            except Exception as e:
                print e

    def edit_lak(self):
        """
            Update ui to diplay params of editable lak
        """
        rows = self.lakTable.selectionModel().selectedRows()

        if len(rows) != 1:
            self.message_to_gui("Selection problem", "please select one lake")
            return

        self.lakAdd.setEnabled(False)
        self.lakDelete.setEnabled(False)
        self.lakSaveEdit.setEnabled(True)
        self.lakCancelEdit.setEnabled(True)

        row = rows[0]

        tmp_lak = self.get_dict_from_row(row.row())

        self.old_id = tmp_lak['lake_id']

        self.lak_table_index = row.row()

        self.lakId.setValue(tmp_lak['lake_id'])
        self.lakSurfdep.setValue(tmp_lak['surfdep'])
        self.lakStages.setValue(tmp_lak['stages'])
        self.lakSsmn.setValue(tmp_lak['ssmn'])
        self.lakSsmx.setValue(tmp_lak['ssmx'])
        self.lakLeakance.setValue(tmp_lak['leakance'])

        self.get_sp(tmp_lak['lake_id'])

    def get_sp(self, lake_id):
        """
            Load stress period params from the database to the table
        """

        sql = "SELECT * FROM laksp_{} WHERE lake_id=?".format(self.model_name)
        result = self.execute_query(sql, (lake_id,), True)

        for idx, res in enumerate(result):

            self.lakSpTable.setItem(idx, 0, QTableWidgetItem(str(res['sp'])))
            self.lakSpTable.setItem(idx, 1, QTableWidgetItem(str(res['prcplk'])))
            self.lakSpTable.setItem(idx, 2, QTableWidgetItem(str(res['evaplk'])))
            self.lakSpTable.setItem(idx, 3, QTableWidgetItem(str(res['rnf'])))
            self.lakSpTable.setItem(idx, 4, QTableWidgetItem(str(res['wthdrw'])))

    def update_lak_table(self, values, old_id=None):
        """
            Update existings table

        Args:
            values (dict): a python dict containing lake info
            old_id (int): change old_Id if necessary

        """

        if not old_id:
            old_id = values['lake_id']

        sql = "UPDATE lak_{} SET surfdep=?, stages=?, ssmn=?, ssmx=?, leakance=?, lake_id=? WHERE lake_id=?".format(self.model_name)

        params = (values['surfdep'], values['stages'], values['ssmn'], values['ssmx'], values['leakance'],
                  values['lake_id'], old_id)

        try:
            self.execute_query(sql, params)
        except IntegrityError:
            return False

        return True

################################################################################
### Load/ create lak layers
################################################################################

    def check_if_exists(self):
        """
            Check if a lak_layer_group is loaded in qgis
        """

        if self.tree.findGroup('lak_layer_group_' + self.model_name):
            self.load_data_from_db()
        else:
            table_name = 'lak_{}'.format(self.model_name)

            sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"

            params = (table_name, )

            res = self.execute_query(sql, params)

            if len(res) == 1:
                self.reload_lak_group()
                self.load_data_from_db()

    def reload_lak_group(self):
        """
            Relaod lak group if exists on the database, but not on the qgis tree
        """
        # Create group to
        group_id = self.legend.addGroup("lak_layer_group_" + self.model_name)

        # load lak table

        sql = "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE ?"
        params = ('%' + self.suffix, )

        res = self.execute_query(sql, params)
        # reload layers _lak
        for layer in res:
            layer_name = layer[0]
            self.add_layer_to_group(layer_name, group_id)

    def load_data_from_db(self):
        """
            load the data from sqlite to gui
        """

        sql = "SELECT * FROM lak_{}".format(self.model_name)
        result = self.execute_query(sql)

        for idx, lake in enumerate(result):
            row = self.lakTable.rowCount()
            self.lakTable.insertRow(row)

            self.backup_idx.append(lake[0])

            self.lakTable.setItem(row, 0, QTableWidgetItem(str(lake[0])))
            self.lakTable.setItem(row, 1, QTableWidgetItem(str(lake[1])))
            self.lakTable.setItem(row, 2, QTableWidgetItem(str(lake[2])))
            self.lakTable.setItem(row, 3, QTableWidgetItem(str(lake[3])))
            self.lakTable.setItem(row, 4, QTableWidgetItem(str(lake[4])))
            self.lakTable.setItem(row, 5, QTableWidgetItem(str(lake[5])))

        sql = "SELECT * from lake_{}".format(self.model_name)

        result = self.execute_query(sql, convert=True)[0]

        self.lakTheta.setValue(result['theta'])
        self.lakNssitr.setValue(result['nssitr'])
        self.lakSscncr.setValue(result['sscncr'])

        # self.lakParams.setEnabled(True)
        # self.lakTableDiv.setEnabled(True)

        self.__enable_frames()

    def __enable_frames(self):
        self.spFrame.setEnabled(True)
        self.lakSpTable.setEnabled(True)
        self.lakParams1.setEnabled(True)
        self.lakParams2.setEnabled(True)
        self.lakButton.setEnabled(True)

    def create_lak_layer(self):
        """
            create new lake layer and add to qgis
        """

        if self.tree.findGroup('lak_layer_group_' + self.model_name):
            self.message_to_gui('LAK layer already exists')
            return

        # get db path
        model_name = self.lakModel.currentText()
        pathfile, _ = futils.getModelInfoByName(model_name)
        self.path = os.path.join(pathfile, model_name + '.sqlite')
        self.model_name = model_name

        self.lak_table = self.lak_table + self.model_name

        # Check if table exists
        self.__check_if_table_exists()

        self.create_general_table()

        # get layer name from db
        lfp_table = "lpf_" + model_name
        layer_list = [' '.join(item) for item in self.execute_query("SELECT name FROM " + lfp_table)]

        # Create group to
        group_id = self.legend.addGroup("lak_layer_group_" + self.model_name)

        layer_list = self.layer_list_order(layer_list)

        for idx, tup in enumerate(layer_list):

            base_layer_name = tup[0]
            new_layer_name = base_layer_name + self.suffix

            # Create a new lake layer
            self.create_new_lak_layer(new_layer_name, base_layer_name, idx)
            # Add new lake layer to qgis
            self.add_layer_to_group(new_layer_name, group_id)

        # add table to qgis lak group

        # self.lakParams.setEnabled(True)
        # self.lakTableDiv.setEnabled(True)

        self.__enable_frames()

        self.message_to_gui("Lake layer created")

    def get_crs_from_model(self, model_name):
        """
            get the crs from modeltable_
        """
        query = "SELECT crs FROM modeltable_{};".format(model_name)
        res = self.execute_query(query)[0]
        return res[0].replace('EPSG:', '')

    def add_layer_to_group(self, layer_name, group_id):
        """
            Load layer from sqlite and add to lake group
        """
        uri = QgsDataSourceURI()
        uri.setDatabase(self.path)
        schema = ''
        table = layer_name
        geom_column = "Geometry"
        uri.setDataSource(schema, table, geom_column)
        display_name = table

        wlayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

        QgsMapLayerRegistry.instance().addMapLayer(wlayer)
        self.legend.moveLayer(wlayer, group_id)

    def add_table_to_group(self, table_name, group_id):
        """
            Load layer from sqlite and add to lake group

            Args:
                table_name (str): name of the table to load
                group_id (int): lak group id
        """
        uri = QgsDataSourceURI()
        uri.setDatabase(self.path)
        uri.setDataSource('', table_name, '')

        table_layer = QgsVectorLayer(uri.uri(), table_name, 'spatialite')

        QgsMapLayerRegistry.instance().addMapLayer(table_layer)
        self.legend.moveLayer(table_layer, group_id)

    def create_general_table(self):
        """
            Create lak table with general params
        """
        sql = "CREATE TABLE IF NOT EXISTS %s (" % self.lak_table
        sql += " name TEXT,"
        sql += " theta REAL,"
        sql += " nssitr INTEGER,"
        sql += " sscncr REAL )"

        self.execute_query(sql)

        sql = "INSERT INTO {} (name, theta, nssitr, sscncr) VALUES(?, ?, ?, ?)".format(self.lak_table)
        params = (self.model_name, self.lakTheta.value(), self.lakNssitr.value(), self.lakSscncr.value())

        self.execute_query(sql, params)

    def create_new_lak_layer(self, new_table_name, base_table_name, layer_id=0):
        """
            Create a new lak layer based on model layers
            Create the new table and copy the data from base layer
        """
        create_table = """
            CREATE TABLE {} (
                PKUID INTEGER PRIMARY KEY,
                Geometry MULTIPOLYGON,
                ID INTEGER,
                ROW INTEGER,
                COL INTEGER,
                LAYER INTEGER DEFAULT 0,
                LAKE INTEGER DEFAULT 0,
                LEAKANCE REAL DEFAULT 0.0
            );

        """.format(new_table_name)

        self.execute_query(create_table)

        crs = self.get_crs_from_model(self.model_name)

        add_geom_column = "SELECT RecoverGeometryColumn('{}', 'Geometry', {}, 'MULTIPOLYGON', 'XY')".format(new_table_name, crs)
        self.execute_query(add_geom_column)

        fill_table = """
            INSERT INTO {}
            SELECT PKUID, Geometry, ID, ROW, COL, {}, 0, 0 FROM {};
        """.format(new_table_name, layer_id, base_table_name)
        self.execute_query(fill_table)

    def __check_if_table_exists(self):
        """
            Check if lak and laksp table exists
        """
        sql = "CREATE TABLE IF NOT EXISTS lak_%s (" % self.model_name
        sql += "lake_id INTEGER UNIQUE PRIMARY KEY, "
        sql += "surfdep REAL, "
        sql += "stages REAL, "
        sql += "ssmn REAL, "
        sql += "ssmx REAL, "
        sql += "leakance REAL"
        sql += ");"

        self.execute_query(sql)

        sql = """CREATE TABLE laksp_{}(

                lake_id INTEGER NOT NULL,
                sp INTEGER NOT NULL,
                prcplk REAL,
                evaplk REAL,
                rnf REAL,
                wthdrw REAL

            )
        """.format(self.model_name)

        self.execute_query(sql)

################################################################################
# New lake
################################################################################

    def add_new_lake(self):
        """
            Read data from spinBox and create a new lake
        """

        lak_params = {
            "lake_id": self.lakId.value(),
            "surfdep": self.lakSurfdep.value(),
            "stages": self.lakStages.value(),
            "ssmn": self.lakSsmn.value(),
            "ssmx": self.lakSsmx.value(),
            "leakance": self.lakLeakance.value(),
            "sp": self.read_sp_data()
        }

        if lak_params['lake_id'] == 0:
            QMessageBox.warning(self, 'Lake error', 'lake id should be different from 0')
            return

        try:
            self.add_lake_to_table(lak_params)
        except IntegrityError:
            QMessageBox.warning(self, 'SQlite integrity error',
                                'A lake with the same ID already exists, please change it')
            return

        row = self.lakTable.rowCount()
        self.lakTable.insertRow(row)

        self.backup_idx.append(lak_params['lake_id'])

        self.lakTable.setItem(row, 0, QTableWidgetItem(str(lak_params['lake_id'])))
        self.lakTable.setItem(row, 1, QTableWidgetItem(str(lak_params['surfdep'])))
        self.lakTable.setItem(row, 2, QTableWidgetItem(str(lak_params['stages'])))
        self.lakTable.setItem(row, 3, QTableWidgetItem(str(lak_params['ssmn'])))
        self.lakTable.setItem(row, 4, QTableWidgetItem(str(lak_params['ssmx'])))
        self.lakTable.setItem(row, 5, QTableWidgetItem(str(lak_params['leakance'])))

        self.clear_sp_table()

        self.clear_lak_params()

        self.message_to_gui("Added new lake")

    def read_sp_data(self):
        """
            Read Stress period data from table
        """
        row_count = self.lakSpTable.rowCount()

        sp_lak = {}

        for row in range(0, row_count):

            idx_sp = int(self.lakSpTable.item(row, 0).text())
            prc = float(self.lakSpTable.item(row, 1).text())
            evap = float(self.lakSpTable.item(row, 2).text())
            rnf = float(self.lakSpTable.item(row, 3).text())
            whtdrw = float(self.lakSpTable.item(row, 4).text())

            sp_lak[idx_sp] = [prc, evap, rnf, whtdrw]

        return sp_lak

    def remove_selected(self):
        """
            Remove selected lake from database
        """
        rows = self.lakTable.selectionModel().selectedRows()

        for row in reversed(rows):
            index = row.row()
            lake_id = int(self.lakTable.item(index, 0).text())
            self.lakTable.removeRow(row.row())

            sql = "DELETE FROM lak_{} WHERE lake_id=?".format(self.model_name)
            self.execute_query(sql, (lake_id,))

            sql = "DELETE FROM laksp_{} WHERE lake_id=?".format(self.model_name)
            self.execute_query(sql, (lake_id,))

            del self.backup_idx[index]

        self.message_to_gui("removed all selected lake")

    def add_lake_to_table(self, params):
        """
            Add new lake to sqlite table

            Args:
                params (dict): python dict containing all lake information
        """

        sql_lak = "INSERT INTO lak_{} (lake_id, surfdep, stages, ssmn, ssmx, leakance) ".format(self.model_name)
        sql_lak += " VALUES (?, ?, ?, ?, ?, ?);"

        par_lak = (params['lake_id'], params['surfdep'], params['stages'], params['ssmn'], params['ssmx'],
                   params['leakance'],)

        self.execute_query(sql_lak, par_lak)

        for sp in params['sp'].keys():

            sp_data = params['sp'][sp]

            sql = "INSERT INTO laksp_{} (lake_id, sp, prcplk, evaplk, rnf, wthdrw) VALUES(?, ?, ?, ?, ?, ?)".format(self.model_name)
            par = (params['lake_id'], sp, sp_data[0], sp_data[1], sp_data[2], sp_data[3])

            self.execute_query(sql, par)

################################################################################
# Utility
################################################################################

    def clear_sp_table(self):
        """
            Clear stress period lak table and fill with
        """
        self.lakSpTable.setRowCount(0)

        for sp in self.sp_list:
            row_idx = self.lakSpTable.rowCount()
            self.lakSpTable.insertRow(row_idx)

            self.lakSpTable.setItem(row_idx, 0, QTableWidgetItem(str(sp)))
            self.lakSpTable.setItem(row_idx, 1, QTableWidgetItem('0'))
            self.lakSpTable.setItem(row_idx, 2, QTableWidgetItem('0'))
            self.lakSpTable.setItem(row_idx, 3, QTableWidgetItem('0'))
            self.lakSpTable.setItem(row_idx, 4, QTableWidgetItem('0'))

    def clear_lak_params(self):
        """
            CLear lake parmas
        """
        self.lakId.setValue(1)
        self.lakSurfdep.setValue(0)
        self.lakStages.setValue(0)
        self.lakSsmn.setValue(0)
        self.lakSsmx.setValue(0)
        self.lakLeakance.setValue(0)

    def get_sp_period(self):
        """
            get sp list from timetable
        """
        sql = "SELECT sp FROM timetable_{}".format(self.model_name)
        res = self.execute_query(sql)

        self.sp_list = [x for xs in res for x in xs]

    def layer_list_order(self, layer_list):
        """
            Read from the base model the bottom value to automatically set the layer level
        """
        res = []

        for layer in layer_list:
            sql = "SELECT bottom FROM {} LIMIT 1".format(layer)
            level = self.execute_query(sql)[0][0]

            res.append((layer, level))

        res.sort(key=lambda tup: tup[1], reverse=True)

        return res

    def execute_query(self, query, params=None, convert=False):
        """
            Query the database

            Args:
                query (str): sql query to execute
                params (tuple): tuple with query params
                convert (bool): if true convert the query resutl to a list of dict
        """

        conn = db.connect(self.path)

        if convert:
            conn.row_factory = dict_factory

        try:
            if params:
                res = conn.execute(query, params).fetchall()
            else:
                res = conn.execute(query).fetchall()
        except Exception as e:
            print e
            conn.commit()
            conn.close()
            raise e

        conn.commit()
        conn.close()

        return res

    def get_dict_from_row(self, index):
        """
            read a dict from table
        """
        tmp = {}

        for idx in range(self.lakTable.columnCount()):

            name = self.lakTable.model().headerData(idx, Qt.Horizontal).lower()
            if name == 'lake_id':
                value = int(self.lakTable.item(index, idx).text())
            else:
                value = float(self.lakTable.item(index, idx).text())

            tmp[name] = value

        return tmp

    def message_to_gui(self, title, message=''):
        """
        """
        self.bar.pushMessage(title, message, level=QgsMessageBar.INFO, duration=3)
