# -*- 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 fileDialog, getVectorLayerByName, getVectorLayerNames, getModelsInfoLists, getModelInfoByName
from freewat.sqlite_utils import getTableNamesList, uploadCSV
from pyspatialite import dbapi2 as sqlite3
#
FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/ui_loadClimateData.ui') )
#
#class CreateAddSPDialog  (QDialog, Ui_addStressPeriodDialog):
class LoadClimateDataDialog (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.createCropTable)

        #csv browse button
        self.btnBrowse.clicked.connect(self.outFilecsv)
        self.manageGui()
##
##
    def manageGui(self):
        self.cmbModelName.clear()
        layerNameList = getVectorLayerNames()
        (modelNameList, pathList) =  getModelsInfoLists(layerNameList)

        self.cmbModelName.addItems(modelNameList)
##
	# function for the choose of the csv table
    def outFilecsv(self):
        (self.OutFilePath) = fileDialog(self)
        self.txtDirectory.setText(self.OutFilePath)
        # if self.OutFilePath is None or self.encoding is None:
            # return
##
    def createCropTable(self):

        # ------------ Load input data  ------------
        modelName = self.cmbModelName.currentText()

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

        dbName = os.path.join(pathfile, modelName + '.sqlite')

        # CSV table loader
        # csv = self.OutFilePath
        # print 'la path ', self.OutFilePath
        # uri = QUrl.fromLocalFile(csv)
        # uri.addQueryItem("type","csv")
        # uri.addQueryItem("geomType","none")
        # csvlayer = QgsVectorLayer(uri.toString(), "ClimateData_" + modelName, "delimitedtext")
        # if csvlayer.isValid():
        #     print 'CSV valid'
        # else:
        #     print 'Error when loading CSV'
		# # 	QgsMapLayerRegistry.instance().addMapLayer(csvl)

        # creating/connecting SQL database object
        con = sqlite3.connect(dbName)
        con.enable_load_extension(True)
        cur = con.cursor()

        tableList = getTableNamesList(dbName)
        tableName = "ClimateData_" + modelName

        if tableName in tableList:
            QMessageBox.warning(self, self.tr('Warning!'), self.tr('Yuo have already created a ClimateData Table \n for model %s !' % modelName))
            return


        # 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(), tableName, "delimitedtext")

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


        # Add the model table into QGis map
        uri = QgsDataSourceURI()
        uri.setDatabase(dbName)
        schema = ''
        table = tableName
        #geom_column = 'the_geom'
        geom_column = None
        uri.setDataSource(schema, table, geom_column)
        display_name = tableName
        tableLayer = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

        QgsMapLayerRegistry.instance().addMapLayer(tableLayer)

        QDialog.reject(self)
