# -*- 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, fileDialog, getFieldNames, load_table
from freewat.sqlite_utils import getTableNamesList, uploadQgisVectorLayer
from pyspatialite import dbapi2 as sqlite3
from collections import OrderedDict
#
FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui/farm_crop_test.ui'))


class CreateFarmCrop(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.updateTable)
        self.updateButton.clicked.connect(self.updateTable)

        self.manageGui()
##
##
    def manageGui(self):
        self.cmbModel.clear()

        # get list of layers in the TOC
        layerNameList = getVectorLayerNames()

        # from the layer in the TOC get the modeltable
        (modelNameList, pathList) =  getModelsInfoLists(layerNameList)

        # add the modeltable to the combobox and assign the modelName to a variable
        self.cmbModel.addItems(modelNameList)
        modelName = self.cmbModel.currentText()

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

        # build the complete path of the database
        self.dbName = os.path.join(pathfile, modelName + '.sqlite')

        # list of table in the database
        tableList = getTableNamesList(self.dbName)

        # fill the combobox with just the Crop table of the database
        l = []
        for i in tableList:
            if 'Crop' in i:
                l.append(i)

        self.cmbCrop.addItems(l)




    def updateTable(self):
        '''
        update the QTableWidget with the fields of the layer selected in the combobox
        '''
        # get the crop table from the combobox
        crop_table = self.cmbCrop.currentText()

        # connection to the database and load as vl the crop table
        uri = QgsDataSourceURI()
        uri.setDatabase(self.dbName)
        schema = ''
        table = crop_table
        geom_column = None
        uri.setDataSource(schema, table, geom_column)

        display_name = 'Copy_Crop_table'
        vl = QgsVectorLayer(uri.uri(), display_name, 'spatialite')

        # provider of the vl
        pr = vl.dataProvider()


        # create a memory layer and fill it with the filtered CropLayer (that is, only ['crop_name', 'crop_id', 'active'] fields and only where 'active' is yes)

        # empty memory layer and provider
        mem = QgsVectorLayer('None', 'memoria', 'memory')
        pr_mem = mem.dataProvider()

        # fields of the original vl trough the provider
        fld = pr.fields()

        # fields of the memory layer
        fld_mem = pr_mem.fields()

        # add the FIELDS to the memory layer with the provider and update the layer
        for i in fld:
            pr_mem.addAttributes([i])

        mem.updateFields()

        # start the editing of the memory layer to be able to add features
        ll = []
        for j in vl.getFeatures():
            fet = QgsFeature()
            fet.setAttributes(j.attributes())
            ll.append(fet)

        # send the features to the provider and commit the changes
        pr_mem.addFeatures(ll)
        mem.commitChanges()

        # create filter so that the provider has just the filtered features
        filter = "active = 'yes'"
        mem.setSubsetString(filter)

        # index of fields that will stay
        crop_name_idx = mem.fieldNameIndex('crop_name')
        crop_id_idx = mem.fieldNameIndex('crop_id')
        active_idx = mem.fieldNameIndex('active')

        # list creation with field indexes that will be delated
        fields_to_delete = [fid for fid in range(len(pr_mem.fields())) if fid != crop_name_idx and fid != crop_id_idx and fid != active_idx]

        # send to provider and update the fields
        pr_mem.deleteAttributes(fields_to_delete)
        mem.updateFields()


        # create list of the vector layer fields
        k = []
        for i in pr_mem.fields():
            k.append(i.name())

        # create list of the vector layer attributes
        v = []
        for i in pr_mem.getFeatures():
            v.append(i.attributes())


        # create OrderedDict of key = fieldname and values = attributes

        fd = OrderedDict(zip(k, map(list, zip(*v))))


        # QTableWidget settings ()
        # column correspond to the length of the fd.keys. Could be extended by adding values len(fd.keys()) + 2
        self.dataTable.setColumnCount(len(fd.keys())+ 2)
        # row length from the length of the values of the dictionary
        self.dataTable.setRowCount(len(fd.values()[0]))
        # column names from the dictionary keys. Could be extended by adding fd.keys() + ['one', 'two']
        self.dataTable.setHorizontalHeaderLabels(fd.keys() + ['one', 'two'])

        # fill the QTable with the dictionary values
        for i in range(len(fd.values())):
            for j in range(len(fd.values()[i])):
                # be aware! all values are unicode! so numbers have to be converted in a second moment
                item = QTableWidgetItem(unicode(fd.values()[i][j]))
                self.dataTable.setItem(j,i,item)



        # BE AWARE THAT THE NUMBERS OF VALUES TO ADD HAVE TO BE THE SAME AS THE COLUMNS ADDED ABOVE!!
        # besides the dictionary values, fill also the remaining columns with some default values
        for i in range(len(fd.values())):
            for j in range(len(fd.values()[i])):
                # be aware! all values are unicode! so numbers have to be converted in a second moment
                items = [QTableWidgetItem(u'1'), QTableWidgetItem(u'2')]
                leng = len(fd.values())
                for ii, jj in enumerate(items):
                    self.dataTable.setItem(j, leng + ii, jj)

        # set the columns width
        self.dataTable.setColumnWidth(0, 128)

        c = 'mathgdteo'
        # try to load the table in the Database
        table_layer = load_table(self.dataTable)
        uploadQgisVectorLayer(self.dbName, table_layer, c)
