# -*- 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 *
import numpy as np
from pyspatialite import dbapi2 as sqlite3
from freewat.freewat_utils import getVectorLayerByName, getVectorLayerNames, getModelsInfoLists, getModelInfoByName, fileDialog
from freewat.sqlite_utils import checkIfTableExists
# load flopy and grid utils
from flopy.modflow import *
from flopy.utils import *


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


class ProgramLocationsDialog(QtGui.QDialog, FORM_CLASS):
#class ModelBuilderDialog(QDialog, Ui_ModelBuilderDialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.saveLocationInDB)

        self.manageGui()

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

        # fill the combobox with the model
        self.cmbModelName.addItems(modelNameList)

    def reject(self):
        QDialog.reject(self)

    def saveLocationInDB(self):

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

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

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

        vl = getVectorLayerByName(locations)

        check = checkIfTableExists(dbName, locations)

        if not check:
            con = sqlite3.connect(dbName)
            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
            vl = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

            QgsMapLayerRegistry.instance().addMapLayer(vl)

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


        if not vl and check:

            # 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
            vl = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

            QgsMapLayerRegistry.instance().addMapLayer(vl)

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


        self.iface.showAttributeTable(vl)

        self.reject()
