# -*- 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, getModelsInfoLists, getModelInfoByName, load_table, fileDialog
from freewat.mdoCreate_utils import createChdLayer, createModelLayer, createChdLayerFromLine
from freewat.sqlite_utils import getTableNamesList, uploadQgisVectorLayer, uploadCSV

#
FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/ui_createCHDLayer.ui') )
#
class CreateCHDLayerDialog(QDialog, FORM_CLASS):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

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

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

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

        self.resize(620, 680)

        self.manageGui()
        self.refreshWidgets()
##
##
    def manageGui(self):
        self.cmbGridLayer.clear()
        self.cmbModelName.clear()
        self.cmbLineLayer.clear()
        layerNameList = getVectorLayerNames()
        layerNameList.sort()

        # Retrieve modelname and pathfile List
        (modelNameList, pathList) =  getModelsInfoLists(layerNameList)

        self.cmbModelName.addItems(modelNameList)

        # fill the Grid combobox with only the _grid layer
        grid_layers = []
        for nametemp in layerNameList:
            if '_grid' in nametemp:
                grid_layers.append(nametemp)


        # create a list of only vector line layers loaded in the TOC
        layerList = QgsMapLayerRegistry.instance().mapLayers()
        lineList = []
        for k, v in layerList.items():
            # check if vector
            if v.type() == 0:
                # check if line
                if v.wkbType() == 2:
                    lineList.append(v.name())

        for l in lineList:
            self.cmbLineLayer.addItem(l)

        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.model_label: ['all'],
            self.cmbModelName: ['all'],
            self.grid_label: ['all'],
            self.cmbGridLayer: ['all'],
            self.line_label: ['line'],
            self.cmbLineLayer: ['line'],
            self.newlay_label: ['all'],
            self.lineNewLayerEdit: ['all'],
            self.from_label: ['line'],
            self.lineLayerNumberFrom: ['line'],
            self.to_label: ['line'],
            self.lineLayerNumberTo: ['line'],
            self.tableBox: ['line'],
            self.csvBox: ['line'],
            self.addCheck: ['line'],
        }

    def refreshWidgets(self):
        '''
        refresh UI widgets depending on the radiobutton chosen
        '''
        for k, v in self.widgetType.items():
            if self.line_radio.isChecked():
                if 'all' or 'line' 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(600, 200)

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

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


    def createCHD(self):

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

        # ------------ Load input data  ------------
        modelName = self.cmbModelName.currentText()
        gridLayer = getVectorLayerByName(self.cmbGridLayer.currentText())
        # name of the new layer
        newName = self.lineNewLayerEdit.text()


        # Remark: pathfile from model table and number of stress periods (nsp) from time table
        layerNameList = getVectorLayerNames()
        (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 + "_chd"

        if layerName in tableList:
            QMessageBox.warning(self, self.tr('Warning!'), self.tr('Table %s already exists!' % layerName))
            return

        # check the Tab index and choose the correct method
        # index == 0 is for the simple mode, no csv and/or additional tables

        # call the create simple CHD method
        if self.radioSingle.isChecked():
            createChdLayer(gridLayer, newName, pathfile, modelName, nsp)

        elif self.line_radio.isChecked():

            # name of the line layer
            lineLayer = getVectorLayerByName(self.cmbLineLayer.currentText())
            # name of the csv that will be loaded in the database
            csv_layer_name = newName + "_table"
            # from_lay and to_lay values as numbers
            from_lay = self.lineLayerNumberFrom.value()
            to_lay = self.lineLayerNumberTo.value()

            # check if the load external csv checkbox is checked
            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')

            # check if the table checkbox is checked
            elif self.tableBox.isChecked():
                QApplication.processEvents()

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

                # load the csvl in the database
                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)

            # call the create CHD from line method
            createChdLayerFromLine(newName, dbName, gridLayer, lineLayer, csvl, nsp, from_lay, to_lay)


        self.progressBar.setMaximum(100)

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