# -*- 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, dataFromCSV, fileDialog
from pyspatialite import dbapi2 as sqlite3
#
FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/ui_addStressPeriod.ui') )
#
class CreateAddSPDialog  (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.addSP)
        self.toolBrowseButton.clicked.connect(self.outFilecsv)
        self.cmbModelName.currentIndexChanged.connect(self.reloadFields)
        self.manageGui()
##
##
    def manageGui(self):
        self.cmbModelName.clear()
        layerNameList = getVectorLayerNames()
        timeList = []
        for tt in layerNameList:
            if 'timetable' in tt:
                timeList.append(tt)
        if len(timeList) < 1:
            message = ''' You don't have any time table defined! \n  Please create a model first!'''
            QMessageBox.warning(self, self.tr('Warning!'), self.tr(message))
            self.reject()
            return

        self.cmbModelName.addItems(timeList)
        self.cmbState.addItems(['Steady State', 'Transient'])


    def reloadFields(self):
        timetable = self.cmbModelName.currentText()
        modelName = timetable[10:]
        (pathfile, nsp ) = getModelInfoByName(modelName)

        self.txtTime.setText(str(nsp))

    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 outFilecsv(self):
        (self.OutFilePath) = fileDialog(self)
        self.txtDirectory.setText(self.OutFilePath)

    def addSP(self):

        # ------------ Load input data  ------------
        timetable = self.cmbModelName.currentText()
        # Retrieve the model name from timetable, formatted as 'modelname_timetable'
        modelName = timetable[10:]

        # Retrieve the modeltable layer and the working directory:
        layerNameList = getVectorLayerNames()

        # 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')
        # creating/connecting SQL database object
        con = sqlite3.connect(dbName)
        # con = sqlite3.connect(":memory:") if you want write it in RAM
        con.enable_load_extension(True)
        cur = con.cursor()


#load the values of SP from the csv files
        try:
        # First retrieve data from GUI:
            length = float(self.txtLength.text())
            time_steps = int(self.txtTimeSteps.text())
            multiplier = float(self.txtMultiplier.text())

            #self.cmbState.clear()
            #self.cmbState.addItems(['SS', 'TR'])
            #state = self.cmbState.currentText()
            state = self.cmbState.currentText()
            if state == 'Steady State':
                state = 'SS'
            else:
                state = 'TR'

            parameters = [length, time_steps, multiplier, state]


            sql_sp = 'SELECT * FROM %s ORDER BY ID DESC LIMIT 1' %timetable
            cur.execute(sql_sp)
            record = cur.fetchall()
            #print record
            #QtGui.QMessageBox.information(None, 'Information', str(record[0]))

            for row in record:
                sp_now = row[0]

            sp_new = sp_now +  1


            sql4 = 'INSERT INTO %s'%timetable
            sql44 = sql4 + '(sp, length, ts, multiplier, state) VALUES (?, ?, ?, ?, ?);'
            cur.execute(sql44, (sp_new, parameters[0], parameters[1], parameters[2], parameters[3]))


        # if the GUI is empty, add the data from the csv file loaded
        except:
            csvlayer = self.OutFilePath
            uri = QUrl.fromLocalFile(csvlayer)
            uri.addQueryItem("type","csv")
            uri.addQueryItem("geomType","none")
            # uri.addQueryItem("delimiter",",")
            # uri.addQueryItem("skipLines","0")
            # uri.addQueryItem("xField","field_1")
            # uri.addQueryItem("yField","field_2")
            csvl = QgsVectorLayer(uri.toString(), 'csv_time', "delimitedtext")
            #adds the CSV file as table in the TOC, useful?!
            #if csvl.isValid():
                #QgsMapLayerRegistry.instance().addMapLayer(csvl)

            # is this really necessary?
            dp = csvl.dataProvider()

            ft_lst = []
            for f in csvl.getFeatures():
                ft_lst.append(f.attributes())


            sql_sp = 'SELECT * FROM %s ORDER BY ID DESC LIMIT 1' %timetable
            cur.execute(sql_sp)
            record = cur.fetchall()

            for row in record:
                sp_now = row[0]

            sp_new = sp_now +  1

            for j in range(len(ft_lst)):
                sql4 = 'INSERT INTO %s'%timetable
                sql44 = sql4 + '(sp, length, ts, multiplier, state) VALUES (?, ?, ?, ?, ?);'
                cur.execute(sql44, (sp_new, ft_lst[j][0], ft_lst[j][1], ft_lst[j][2], ft_lst[j][3]))
                sp_new +=1


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

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