# -*- 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 getFieldNames, getVectorLayerByName, getVectorLayerNames, fileDialog, getModelsInfoLists, getModelInfoByName
from freewat.mdoCreate_utils import createHobLayer
from freewat.sqlite_utils import getTableNamesList
from freewat.oat import config

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

class CreateHOBLayerDialog(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.createHob)

        self.manageGui()

        self.cmbPointLayer.currentIndexChanged.connect(self.reloadFields)
##
##
    def manageGui(self):
        self.cmbGridLayer.clear()
        self.cmbModelName.clear()
        self.cmbPointLayer.clear()
        layerNameList = getVectorLayerNames()
        layerNameList.sort()

        self.ckOat.stateChanged.connect(self.toggle_layout)

        (modelNameList, pathList) =  getModelsInfoLists(layerNameList)

        self.cmbModelName.addItems(modelNameList)
        self.cmbPointLayer.addItems(layerNameList)

        # 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)
##
    def reloadFields(self):
        self.cmbName.clear()
        self.cmbBottom.clear()
        self.cmbTop.clear()
        player = getVectorLayerByName(self.cmbPointLayer.currentText())
        if not player:
            return
        self.cmbName.addItems(getFieldNames(player))
        self.cmbBottom.addItems(getFieldNames(player))
        self.cmbTop.addItems(getFieldNames(player))

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

##
    def createHob(self):

        # ------------ Load input data  ------------

        newName = self.lineNewLayerEdit.text()
        gridLayer = getVectorLayerByName(self.cmbGridLayer.currentText())
        pointLayer = getVectorLayerByName(self.cmbPointLayer.currentText())
        modelName = self.cmbModelName.currentText()
        # List of name for fileds to be included in MDO
        # Ordered in this way: [Name, ZTop, ZBot, Head, Time]
        pointFields = []
        pointFields.append(self.cmbName.currentText())
        pointFields.append(self.cmbTop.currentText())
        pointFields.append(self.cmbBottom.currentText())

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

        if newName == "":
            QMessageBox.warning(self, "New layer name", 'Please insert a name for the new layer')
            return

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

        use_oat = self.ckOat.isChecked()

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

        if use_oat:
            # Create a HOB Layer using OAT sensors
            pointLayer = getVectorLayerByName(config.oat_layer_name)
            createHobLayer(newName, dbName, gridLayer, pointLayer, ['name', 'topscreen', 'bottomscreen'], use_oat)
        else:
            # Create a HOB Layer, call the main funcion imported at the beginning of the file
            createHobLayer(newName, dbName, gridLayer, pointLayer, pointFields, use_oat)

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

    def toggle_layout(self, state):

        if state == Qt.Checked:
            self.fieldFrame.setEnabled(False)
        else:
            self.fieldFrame.setEnabled(True)
