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

#******************************************************************************
#
# Freewat
# ---------------------------------------------------------
#
#
# Copyright (C) 2014 - 2015 Iacopo Borsi (iacopo.borsi@tea-group.com)
#
# This source 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 code 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.
#
# A copy of the GNU General Public License is available on the World Wide Web
# at <http://www.gnu.org/licenses/>. You can also obtain it by writing
# to the Free Software Foundation, 51 Franklin Street, Suite 500 Boston,
# MA 02110-1335 USA.
#
#******************************************************************************

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import os
from PyQt4 import QtGui, uic
from freewat.freewat_utils import getVectorLayerByName, getVectorLayerNames, fileDialog, getModelsInfoLists, getModelInfoByName, load_table, getVectorSingleFeature, getVectorMultiFeature, pop_message
from freewat.mdoCreate_utils import createRivLayer, createMultiRivLayer
from freewat.sqlite_utils import getTableNamesList, uploadQgisVectorLayer, uploadCSV

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


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

        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.createRiver)

        # csv browse button
        self.toolBrowseButton.clicked.connect(self.outFilecsv)

        self.radioSingle.toggled.connect(self.manageGui)
        self.radioSingle.toggled.connect(self.refreshWidgets)

        self.resize(620, 680)

        self.manageGui()

    def manageGui(self):

        self.cmbGridLayer.clear()
        self.cmbModelName.clear()
        self.cmbRiverLayer.clear()
        layerNameList = getVectorLayerNames()
        layerNameList.sort()

        if self.radioSingle.isChecked():
            lineLayer = getVectorSingleFeature()
            lineLayer.sort()
        else:
            lineLayer = getVectorMultiFeature()
            lineLayer.sort()

        # retrieve information about model and stress periods
        (modelNameList, pathList) = getModelsInfoLists(layerNameList)

        self.cmbModelName.addItems(modelNameList)
        self.cmbRiverLayer.addItems(lineLayer)

        grid_layers = []
        for nametemp in layerNameList:
            if '_grid' in nametemp:
                grid_layers.append(nametemp)

        self.cmbGridLayer.addItems(grid_layers)

        # widget dictionary. key is UI widget name, value depends on the label (all = single AND multi, single =just single)
        self.widgetType = {
            self.cmbModelName: ['all'],
            self.cmbGridLayer: ['all'],
            self.cmbRiverLayer: ['all'],
            self.lineNewLayerEdit: ['all'],
            self.labelLayer_7: ['single'],
            self.lineLayerNumber: ['single'],
            self.labelLayer_5: ['single'],
            self.lineWidth: ['single'],
            self.labelLayer_8: ['single'],
            self.lineRiverSegment: ['single'],
            self.tableBox: ['single'],
            self.csvBox: ['single'],
            self.addCheck: ['single'],
        }

    def refreshWidgets(self):
        '''
        refresh UI widgets depending on the radiobutton chosen
        '''

        for k, v in self.widgetType.items():
            if self.radioSingle.isChecked():
                if 'all' or 'single' in v:
                    active = True
                k.setEnabled(active)
                k.setVisible(active)
                self.resize(620, 680)

            else:
                active = 'all' in v
                k.setEnabled(active)
                k.setVisible(active)
                self.resize(620, 400)

	# function for the choose of the csv table
    def outFilecsv(self):
        (self.OutFilePath) = fileDialog(self)
        self.txtDirectory.setText(self.OutFilePath)

    def reject(self):
        QDialog.reject(self)

    def createRiver(self):

        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)
        self.progressBar.setValue(0)

        # ------------ Load input data  ------------

        newName = self.lineNewLayerEdit.text()
        gridLayer = getVectorLayerByName(self.cmbGridLayer.currentText())
        riverLayer = getVectorLayerByName(self.cmbRiverLayer.currentText())
        modelName = self.cmbModelName.currentText()

        # Remark: pathfile from model table and number of stress periods (nsp) from time table
        (pathfile, nsp) = getModelInfoByName(modelName)

        # Retrieve the information of the model and the name
        dbName = os.path.join(pathfile, modelName + '.sqlite')
        tableList = getTableNamesList(dbName)
        layerName = newName + "_riv"

        if layerName in tableList:
            pop_message(self.tr('Table {} already exists!'.format(layerName)), self.tr('warning'))
            return

        if self.radioSingle.isChecked():

            xyz = self.lineRiverSegment.value()
            width = self.lineWidth.value()
            layer = self.lineLayerNumber.value()

            # name of the csv that will be loaded in the database
            csv_layer_name = layerName + "_table"

            if self.csvBox.isChecked():
                # hack to convert the Qtext of the combobox in something like ',', else the upload in the db will fail
                column = repr(str(self.cmb_colsep.currentText()))

                # convert the decimal separator in a valid input for the uploadCSV function
                if self.cmb_decsep.currentText() == '.':
                    decimal = 'POINT'
                else:
                    decimal = 'COMMA'

                # hack to convert the Qtext of the combobox in something like ',', else loading in QGIS of the table will fail
                decimal2 = repr(self.cmb_decsep.currentText())

                # CSV table loader
                csvlayer = self.OutFilePath
                uri = QUrl.fromLocalFile(csvlayer)
                uri.addQueryItem("geomType", "none")
                uri.addQueryItem("delimiter", column)
                uri.addQueryItem("decimal", decimal2)
                csvl = QgsVectorLayer(uri.toString(), csv_layer_name, "delimitedtext")

                # upload the csv in the database by specifing the decimal and column separators
                uploadCSV(dbName, csvlayer, csv_layer_name, decimal_sep=decimal, column_sep=column, text_sep='DOUBLEQUOTE', charset='CP1250')

            elif self.tableBox.isChecked():
                QApplication.processEvents()

                # convert the QTableWiget parameters in a QgsVectorLayer
                csvl = load_table(self.tableWidget)

                uploadQgisVectorLayer(dbName, csvl, csv_layer_name)

            else:
                pop_message(self.tr('Please fill manually the table or load an external csv file'), self.tr('warning'))
                return

            # load table (either if csv layer or filled in the table) in the TOC
            if self.addCheck.isChecked():
                    # connect to the DB and retireve all the information
                    uri = QgsDataSourceURI()
                    uri.setDatabase(dbName)
                    schema = ''
                    table = csv_layer_name
                    geom_column = None
                    uri.setDataSource(schema, table, geom_column)
                    display_name = csv_layer_name
                    tableLayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

                    # add the layer to the TOC
                    QgsMapLayerRegistry.instance().addMapLayer(tableLayer)

            createRivLayer(newName, dbName, gridLayer, riverLayer, csvl, width, layer, xyz, nsp)

        else:
            createMultiRivLayer(newName, dbName, gridLayer, riverLayer, nsp)

        self.progressBar.setMaximum(100)

        # Close the dialog window after the execution of the algorithm
        self.reject()
