# -*- 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.gui import QgsGenericProjectionSelector
import os
from PyQt4 import QtGui, uic
from freewat.freewat_utils import *
from freewat.mdoCreate_utils import createModel
import datetime
from pyspatialite import dbapi2 as sqlite3

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

#class CreateModelDialog(QDialog, Ui_CreateModelDialog):
class CreateModelDialog(QDialog, FORM_CLASS):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)
        
        self.projSelector = QgsGenericProjectionSelector()
        self.OutFilePath = None
        self.encoding = None
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.createModel)
        self.srButton.clicked.connect(self.openSr)

        self.tlBttnWorkingDir.clicked.connect(self.outFileDir)

        self.manageGui()

    def manageGui(self):

        self.cmbBxLengthUnit.addItems(['m', 'cm', 'ft', 'undefined'])
        self.cmbBxTimeUnit.addItems(['sec', 'min', 'hour', 'day', 'month', 'year', 'undefined'])
        self.cmbState.addItems(['Steady State', 'Transient'])

    def outFileDir(self):
        (self.OutFilePath, self.encoding) = dirDialog(self)
        #see the current working directory in the text box
        self.txtDirectory.setText(self.OutFilePath)
        if self.OutFilePath is None or self.encoding is None:
            return

    def openSr(self):
        self.projSelector.exec_()
        self.srText.setText(self.projSelector.selectedAuthId())

    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 createModel(self):


        modelName = self.bxDBname.text()
        lengthString = self.cmbBxLengthUnit.currentText()
        timeString = self.cmbBxTimeUnit.currentText()
        workingDir = self.txtDirectory.text()
        crs = self.srText.text()
        isChild = 1.0

        if not crs or not workingDir:
            pop_message(self.tr('CRS and working dir must be defined'), self.tr('warning'))
            return

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

        #Add SP parameters
        length = float(self.txtLength.text())
        time_steps = int(self.txtTimeSteps.text())
        multiplier = float(self.txtMultiplier.text())

        state = self.cmbState.currentText()
        if state == 'Steady State':
            state = 'SS'
        else:
            state = 'TR'

        timeParameters  = [length, time_steps, multiplier, state]

        # Info on initial time
        init_time = self.dateTimeEdit.time()
        init_date = self.dateTimeEdit.date()

        initTimeString = init_time.toString()
        initDateString = init_date.toString('yyyy-MM-dd')

        createModel(modelName, workingDir, isChild, lengthString, timeString, timeParameters, initDateString, initTimeString,  crs)


        #program location executables

        # creating/connecting SQL database object
        dbName = os.path.join(workingDir, modelName + '.sqlite')

        con = sqlite3.connect(dbName)
        # con = sqlite3.connect(":memory:") if you want write it in RAM
        con.enable_load_extension(True)
        cur = con.cursor()
        # Initialise spatial db

        # # List of available code (to be updated at any insert of NEW capability)
        self.codeslist = ['MF2005', 'MFOWHM', 'MF-NWT', 'MT3DMS', 'MT3D-USGS', 'SEAWAT', 'UCODE', 'ZONE', 'MODPATH']

        locations = 'prg_locations_' + modelName

        sqlcreate = 'CREATE TABLE "%s" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "code" varchart(20), "executable" varchar(200));'%locations

        cur.execute(sqlcreate)

        sqlinsert = 'INSERT INTO %s'%locations
        i = 0
        for c in self.codeslist:
            cur.execute(sqlinsert + ' (code, executable) VALUES (?, ?);', (c, ''))
            i += 1


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

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

        QgsMapLayerRegistry.instance().addMapLayer(tableLayer)

        # set the executable column as a FileName, user can directly browse for files in the Attribute Table
        tableLayer.setEditorWidgetV2(2,'FileName')

        self.progressBar.setMaximum(100)

        messaggio = 'DB Model is saved in ' + workingDir
        Logger.information(None, 'Information', '%s' % (messaggio))


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