# -*- 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.
#
#******************************************************************************
import os
from PyQt4 import QtGui, uic
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from pyspatialite import dbapi2 as sqlite3
from freewat.freewat_utils import dirDialog, getVectorLayerNames, getModelsInfoLists, getModelInfoByName, ModelPath, pop_message
import sys

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


class UpdateWorkingDirectory(QtGui.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.updateWorkingFolder)
        self.browseWorking.clicked.connect(self.outFileDir)
        self.manageGui()


    def manageGui(self):
        self.cmbModelName.clear()
        layerNameList = getVectorLayerNames()
        (modelNameList, pathList) = getModelsInfoLists(layerNameList)

        self.cmbModelName.addItems(modelNameList)


    # open the dialog to choose the new working directory
    def outFileDir(self):
        (self.OutFilePath, self.encoding) = dirDialog(self)
        #see the current working directory in the text box
        self.workingDirPath.setText(self.OutFilePath)
        if self.OutFilePath is None or self.encoding is None:
            return


    def updateWorkingFolder(self):

        # get the modelName from the model combobox
        modelName = self.cmbModelName.currentText()

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

        path = ModelPath()

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

        # get the new working directory from the QlineEdit
        newWorkingDir = self.workingDirPath.text()

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

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

        # get the whole modelTable name
        modelTable = 'modeltable_' + modelName

        # query for SL
        sqlstrg = 'UPDATE "%s" SET working_dir = "%s";'%(modelTable, newWorkingDir)
        cur.execute(sqlstrg)

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

        pop_message(self.tr('Your Working directory path has been updated'), self.tr('information'))
        # QtGui.QMessageBox.information(None, self.tr('Information'), self.tr('Your Working directory path has been updated'))

        self.reject()
