# -*- 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, getModelNlayByName, getFieldNames, ComboStyledItemDelegate
from freewat.mdoCreate_utils  import createMnwLayer
from freewat.sqlite_utils import getTableNamesList
from pyspatialite import dbapi2 as sqlite3
#
#
FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/ui_createMNWLayer.ui') )
#
#class CreateWELayerDialog(QDialog, Ui_CreateWELLayerDialog):
class CreateMNWLayerDialog(QDialog, FORM_CLASS):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)
        self.buttonBox_MDO.rejected.connect(self.reject)
        self.buttonBox_MDO.button(QDialogButtonBox.Ok).clicked.connect(self.createMNW)
        self.buttonBox_Table.rejected.connect(self.reject)
        self.buttonBox_Table.button(QDialogButtonBox.Ok).clicked.connect(self.createMNW_Table)
        self.cmbModelName.currentIndexChanged.connect(self.reloadFieldsModel)
        self.cmbMNW.currentIndexChanged.connect(self.reloadFields )
        self.manageGui()
##
##
    def manageGui(self):
        self.cmbGridLayer.clear()
        self.cmbModelName.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)

        self.cmbGridLayer.addItems(grid_layers)


        mnwlist = []
        for name in layerNameList:
            if '_mnw' in name:
                mnwlist.append(name)

        self.cmbMNW.addItems(mnwlist)

##
    def defineListModel(self, laylist):
        nlay = len(laylist)
        model = QtGui.QStandardItemModel(nlay, 1)# nsp rows, 1 col
        it0 = QtGui.QStandardItem('Select Layer(s) where Well is active')
        for i, sp  in enumerate(laylist):
            item = QtGui.QStandardItem(str(sp))
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            item.setData(Qt.Unchecked, Qt.CheckStateRole)
            model.setItem(i+1, 0, item)
        model.setItem(0,it0)
        return model

    # @pyqtSlot(QStandardItem)
    # def addLayertoList_1(self, item):
    #     state = item.checkState()
    #     print 'state --- testo', item.checkState(), item.text()
    #     if state == 2:
    #         lay = int(item.text())
    #         self.selectedLayers_1[lay - 1] = lay
    # def addLayertoList_2(self, item):
    #     state = item.checkState()
    #     print 'state --- testo 2', item.checkState(), item.text()
    #     if state == 2:
    #         lay = int(item.text())
    #         self.selectedLayers_2[lay - 1] = lay
    # def addLayertoList_3(self, item):
    #     state = item.checkState()
    #     print 'state --- testo', item.checkState(), item.text()
    #     if state == 2:
    #         lay = int(item.text())
    #         self.selectedLayers_3[lay - 1] = lay

##
    def reloadFieldsModel(self):
        # get and save the model info
        self.modelName = self.cmbModelName.currentText()
        self.nlay = getModelNlayByName(self.modelName)
        (self.pathfile, self.nsp ) = getModelInfoByName(self.modelName)

##
    def reloadFields(self):
        welllayer = getVectorLayerByName(self.cmbMNW.currentText())
        idlist = []
        for f in welllayer.getFeatures():
            idlist.append(f['WELLID'])
        self.cmbWellID_1.clear()
        self.cmbWellID_1.addItems(idlist)
        self.cmbWellID_2.clear()
        self.cmbWellID_2.addItems(idlist)
        self.cmbWellID_3.clear()
        self.cmbWellID_3.addItems(idlist)

        # # get and save the model info
        # self.modelName = self.cmbModelName.currentText()
        # self.nlay = getModelNlayByName(self.modelName)
        # (self.pathfile, self.nsp ) = getModelInfoByName(self.modelName)
        # create laylist
        laylist = [i for i in range(1, self.nlay + 1)]

        # Update nlay combo
        self.cmbLayers_1.clear()
        self.modelNlay_1 = self.defineListModel(laylist)
        self.cmbLayers_1.setModel(self.modelNlay_1)
        self.cmbLayers_1.setItemDelegate(ComboStyledItemDelegate())

        self.cmbLayers_2.clear()
        self.modelNlay_2 = self.defineListModel(laylist)
        self.cmbLayers_2.setModel(self.modelNlay_2)
        self.cmbLayers_2.setItemDelegate(ComboStyledItemDelegate())

        self.cmbLayers_3.clear()
        self.modelNlay_3 = self.defineListModel(laylist)
        self.cmbLayers_3.setModel(self.modelNlay_3)
        self.cmbLayers_3.setItemDelegate(ComboStyledItemDelegate())
##
##
    def reject(self):
        QDialog.reject(self)
##
    def restoreGui(self):
        self.progressBar.setFormat("%p%")
        self.progressBar.setRange(0, 1)
        self.progressBar.setValue(0)
        self.cancelButton.clicked.disconnect(self.stopProcessing)
        self.okButton.setEnabled(True)
##
    def createMNW(self):

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

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

        # Retrieve the name of the new layer from Text Box
        name = self.textEdit.text()

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

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

        # Create a MNW Layer
        createMnwLayer(gridLayer, name, pathfile, modelName, nsp)

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

##
    def createMNW_Table(self):

        # ------------ Load input data  ------------
        modelName = self.modelName
        #
        welllayer = getVectorLayerByName(self.cmbMNW.currentText())
        #
        nlay, nsp, pathfile  = self.nlay, self.nsp, self.pathfile

        # Retrieve the information of the model and the name
        dbname = pathfile + '/' + modelName + ".sqlite"
        tableList = getTableNamesList(dbname)

        tableName =  'mnwtable_' + modelName

        # creating/connecting SQL database object
        con = sqlite3.connect(dbname)
        con.enable_load_extension(True)
        cur = con.cursor()
        #
        isNew = False
        if tableName not in tableList:
            isNew = True
            # create new table
            SQLstring = 'CREATE TABLE "%s" ("idwell" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "well_id" varchar(20), "layer" integer, "Rw" float, "B" float, "C" float, "P" float );'%tableName
            cur.execute(SQLstring)
        #

        # Wells properties
        wellselection = [self.radioWell_1, self.radioWell_2, self.radioWell_3]
        cbmIdselection = [self.cmbWellID_1, self.cmbWellID_2, self.cmbWellID_3 ]
        layerSelection = [self.modelNlay_1, self.modelNlay_2, self.modelNlay_3 ]
        Rwselection = [self.txtRw_1.text(), self.txtRw_2.text(), self.txtRw_3.text() ]
        Bselection = [self.txtB_1.text(), self.txtB_2.text(), self.txtB_3.text()]
        Cselection = [self.txtC_1.text(), self.txtC_2.text(), self.txtC_3.text()]
        Pselection = [self.txtP_1.text(), self.txtP_2.text(), self.txtP_3.text()]
        for i in range(3):
            # check if the current combo box is selected (among 3 in the GUI)
            if wellselection[i].isChecked():
                # Get Well ID
                wellId = cbmIdselection[i].currentText()
                # Get Layers number from Checkable List Combo
                layers = [0 for h in range(self.nlay)]
                j= 1
                for row in range(1, layerSelection[i].rowCount() ):
                    item = layerSelection[i].item(row)
                    if item.checkState() == 2 :
                        layers[j-1] = j
                    j += 1

                # # Get Well Equation Coefficients
                rw = float(Rwselection[i])
                bb = float(Bselection[i])
                cc = float(Cselection[i])
                pp = float(Pselection[i])
                # Insert or update parameter in table
                for k in range(len(layers)):
                    if layers[k] != 0:
                        sqlstr = 'INSERT INTO %s'%tableName
                        cur.execute(sqlstr + ' (well_id , layer , Rw , B , C , P ) VALUES (? , ? , ? , ? , ? , ? );', (wellId, layers[k], rw, bb, cc, pp ) )

        # Close SpatiaLiteDB
        cur.close()
        # Save the changes
        con.commit()
        # Close connection
        con.close()

        # Add the model table into QGis map, if this is the first time!!
        if isNew:
            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)





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