bool 
TeExportLayerToShapefile(TeLayer* layer, const string& baseName)
{
  	if (!layer)
		return false;

	string fbase = baseName;
	if (baseName.empty())
		fbase = layer->name();

	TeTheme* tempTheme = new TeTheme();
	tempTheme->layer(layer);
	tempTheme->collectionTable("");
	tempTheme->collectionAuxTable("");
	tempTheme->setAttTables(layer->attrTables());

	TeQuerierParams qPar(true, true);
	qPar.setParams(tempTheme);

	TeQuerier* tQuerier = new TeQuerier(qPar);
	bool res = TeExportQuerierToShapefile(tQuerier, baseName);
	delete tQuerier;
	delete tempTheme;
    return res ;
}
void VoronoiWindow::themeComboBox_activated(const QString& themeName)
{
    TeTheme* theme = getTheme(themeName.latin1());
    if(theme == 0)
        return;
    // Updates the combo box with delimiters...
    TeLayer* layer = theme->layer();
    boxComboBox->setCurrentText(layer->name().c_str());
    
    // Lists attributes on the weightComboBox
    weightComboBox->clear();
    //if (text=="") text=themeComboBox->currentText().latin1();
    TeTable *attrTable = &layer->attrTables()[0];
    TeAttributeList * attrList=&attrTable->attributeList();
    for (std::vector<TeAttribute>::iterator i=attrList->begin(); i!=attrList->end();++i) {
        cout<<i->rep_.name_<<endl;
        weightComboBox->insertItem(i->rep_.name_);
    }
}
bool
TeExportShapefile(TeLayer* layer, const string& shpFileName, const string& tableName, const string& restriction)
{
  	if (!layer || shpFileName.empty())
		return false;

	// check if asked table exist
	TeAttrTableVector& vTables = layer->attrTables();
	TeAttrTableVector::iterator it = vTables.begin();
	while (it != vTables.end())
	{
		if (it->name() == tableName) 
			break;
		++it;
	}
	if (it == vTables.end())
		return false;
	TeAttrTableVector askedTable;
	askedTable.push_back(*it);

	TeTheme* tempTheme = new TeTheme();
	tempTheme->attributeRest(restriction);
	tempTheme->layer(layer);
	tempTheme->collectionTable("");
	tempTheme->collectionAuxTable("");
	tempTheme->setAttTables(askedTable);

	TeQuerierParams qPar(true, true);
	qPar.setParams(tempTheme);

	TeQuerier* tQuerier = new TeQuerier(qPar);
	bool res = TeExportQuerierToShapefile(tQuerier, shpFileName);
	delete tQuerier;
	delete tempTheme;
    return res ;
}
bool updateDB20To30(TeDatabase* db, string& errorMessage)
{
	TeAttribute fattr;

	// ----- te_grouping 

	if(db->columnExist("te_grouping", "grouping_function", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeSTRING;
		atRep.name_ = "grouping_function";
		atRep.numChar_ = 10;
		if(db->addColumn("te_grouping", atRep) == false)
		{
			errorMessage = "The column grouping_function could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		string upd;
		if(db->columnExist("te_theme_application", "group_function", fattr))
		{
			upd =	" UPDATE te_grouping g, te_theme_application ta ";
			upd +=	" SET g.grouping_function = ta.group_function ";
			upd +=	" WHERE ta.theme_id = g.theme_id ";

			if(!db->execute (upd))
			{
				errorMessage = db->errorMessage();
				return false;
			}

			db->deleteColumn("te_theme_application", "group_function");
		}
		else
		{
			upd =	" UPDATE te_grouping g ";
			upd +=	" SET g.grouping_function = 'AVG' ";
			
			if(!db->execute (upd))
			{
				errorMessage = db->errorMessage();
				return false;
			}
		}
	}

	// ----- te_theme_application

	if(db->columnExist("te_theme_application", "chart_function", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeSTRING;
		atRep.name_ = "chart_function";
		atRep.numChar_ = 10;
		if(db->addColumn("te_theme_application", atRep) == false)
		{
			errorMessage = "The column chart_function could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}
		db->execute("UPDATE te_theme_application SET chart_function = 'AVG'");
	}

	// ----- te_theme 
	if(db->columnExist("te_theme", "visible_rep", fattr) == false)
	{
		TeAttributeRep atRep;
		atRep.type_ = TeINT;
		atRep.name_ = "visible_rep";
		if(db->addColumn("te_theme", atRep) == false)
		{
			errorMessage = "The column visible_rep could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		atRep.name_ = "enable_visibility";
		if(db->addColumn("te_theme", atRep) == false)
		{
			errorMessage = "The column enable_visibility could not be appended!\n";
			errorMessage += db->errorMessage();
			return false;
		}

		string upd = " UPDATE te_theme t, te_theme_application ta ";
		upd +=       " SET t.visible_rep = ta.visible_rep ";
		upd +=       " WHERE ta.theme_id = t.theme_id ";
		if(!db->execute (upd))
		{
			errorMessage = db->errorMessage();
			return false;
		}

		upd =		 " UPDATE te_theme t, te_theme_application ta ";
		upd +=       " SET t.enable_visibility = ta.enable_visibility ";
		upd +=       " WHERE ta.theme_id = t.theme_id ";
		if(!db->execute (upd))
		{
			errorMessage = db->errorMessage();
			return false;
		}
			
		db->deleteColumn("te_theme_application", "visible_rep");
		db->deleteColumn("te_theme_application", "enable_visibility");
	}

	//if for ADO passar todas as tabelas para aceitar comprimento iguel a zero!!!
	if(db->dbmsName() == "Ado")
	{
		//te_layer 
		//te_layer_table
		db->allowEmptyString ("te_layer_table", "attr_initial_time");
		db->allowEmptyString ("te_layer_table", "attr_final_time");
		db->allowEmptyString ("te_layer_table", "user_name");

		//te_representation
		db->allowEmptyString ("te_representation", "description");
		
		//te_view
		db->allowEmptyString ("te_view", "user_name");

		//te_visual
		db->allowEmptyString ("te_visual", "lib_name");
		db->allowEmptyString ("te_visual", "contour_lib_name");
		db->allowEmptyString ("te_visual", "family");

		//te_legend
		db->allowEmptyString ("te_legend", "lower_value");
		db->allowEmptyString ("te_legend", "upper_value");
		db->allowEmptyString ("te_legend", "label");
		
		//te_theme
		db->allowEmptyString ("te_theme", "generate_attribute_where");
		db->allowEmptyString ("te_theme", "generate_spatial_where");
		db->allowEmptyString ("te_theme", "generate_temporal_where");
		db->allowEmptyString ("te_theme", "collection_table");

		//te_grouping
		db->allowEmptyString ("te_grouping", "grouping_attr");
		db->allowEmptyString ("te_grouping", "grouping_norm_attr");
		db->allowEmptyString ("te_grouping", "grouping_function");

		//te_theme_application
		db->allowEmptyString ("te_theme_application", "refine_attribute_where");
		db->allowEmptyString ("te_theme_application", "refine_spatial_where");
		db->allowEmptyString ("te_theme_application", "refine_temporal_where");
		db->allowEmptyString ("te_theme_application", "grouping_color");
		db->allowEmptyString ("te_theme_application", "pie_dimension_attr");
		db->allowEmptyString ("te_theme_application", "text_table");
		db->allowEmptyString ("te_theme_application", "chart_function");
	}

	//------------ auxiliary collection  
	TeDatabasePortal* portal = db->getPortal();
	if(!portal)
		return false;

	string sql = " SELECT theme_id, visible_rep FROM te_theme ";
	if(!portal->query(sql))
	{
		delete portal;
		return true;
	}

	while(portal->fetchRow ())
	{
		string	themeId = portal->getData(0);
		int		visRep  = atoi(portal->getData(1));

		string collExtTable = "te_collection_"+ themeId +"_aux";
		
		if	((db->tableExist("te_collection_"+ themeId)) && 
			((visRep & TeRASTER) != TeRASTER)			 && 
			(!db->tableExist(collExtTable)))
		{
			TeTheme* theme = new TeTheme();
			theme->id(atoi(themeId.c_str()));
			if(!db->loadTheme (theme))
			{
				delete portal;
				return false;
			}

			string up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 0";
			up += " WHERE c_object_status <> " + Te2String(theme->pointingLegend().id());
			up += " AND c_object_status <> " + Te2String(theme->queryLegend().id());
			up += " AND c_object_status <> " + Te2String(theme->queryAndPointingLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 1";
			up += " WHERE c_object_status = " + Te2String(theme->pointingLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 2";
			up += " WHERE c_object_status = " + Te2String(theme->queryLegend().id());
			db->execute(up);

			up = "UPDATE " + theme->collectionTable() + " SET c_object_status = 3";
			up += " WHERE c_object_status = " + Te2String(theme->queryAndPointingLegend().id());
			db->execute(up);

			if ((!theme->createCollectionAuxTable()) || (!theme->populateCollectionAux())) 
			{
				errorMessage = "Fail to mount the auxiliary table of the collection!\n";
				errorMessage += db->errorMessage();
				delete portal;
				return false;
			}

			theme->collectionAuxTable(collExtTable);
			theme->addThemeTable(collExtTable);
					
			string oldTCE = theme->collectionTable() + "_ext";
			if (db->tableExist(oldTCE))
			{
				string delTable = "DROP TABLE " + oldTCE;
				db->execute(delTable);
			}
		}
		
	}
	//------------ end auxiliary collection  

	portal->freeResult();

	//------------ text table  
	// if text table have not text visual table associated, create it
	string sel = "SELECT geom_table FROM te_representation WHERE";
	sel += " geom_type = " + Te2String(TeTEXT);
	if(portal->query(sel))
	{
		while(portal->fetchRow())
		{
			string table = portal->getData(0);
			string tvis = table + "_txvisual";
			if(!db->tableExist(tvis))
			{
				TeAttributeList atl;
				TeAttribute		at;

				at.rep_.name_ = "geom_id";
				at.rep_.type_ = TeINT;
				at.rep_.numChar_ = 0;
				at.rep_.isPrimaryKey_ = true;
				atl.push_back(at);

				at.rep_.isPrimaryKey_ = false;
				at.rep_.name_ = "dot_height";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "fix_size";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "color";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				at.rep_.name_ = "family";
				at.rep_.type_ = TeSTRING;
				at.rep_.numChar_ = 128;
				atl.push_back(at);

				at.rep_.name_ = "bold";
				at.rep_.type_ = TeINT;
				at.rep_.numChar_ = 0;
				atl.push_back(at);

				at.rep_.name_ = "italic";
				at.rep_.type_ = TeINT;
				atl.push_back(at);

				db->createTable(tvis, atl);
				string fk = "fk_" + tvis;
				db->createRelation(fk, tvis, "geom_id", table, "geom_id", true);
				string ins = "INSERT INTO " + tvis + " (geom_id) SELECT geom_id FROM " + table;
				db->execute(ins);

				string popule = "UPDATE " + tvis;
				popule += " SET dot_height = 12";
				popule += ", fix_size = 0";
				popule += ", color = 16711680";
				popule += ", family = 'verdana'";
				popule += ", bold = 1";
				popule += ", italic = 0";
				if(!db->execute(popule))
				{
					errorMessage = "Fail to generate the text visual table!\n";
					errorMessage += db->errorMessage();
					delete portal;
					return false;;
				}
			}
		}
	}
	//------------ end text table  
	delete portal;
	return true;
}
void VoronoiWindow::okPushButton_clicked()
{
    std::string layerName = layerNameLineEdit->text().utf8();	
	if(layerName.empty())
	{
		QMessageBox::information(this, tr("Information"), tr("Please, define a name to result Layer."));
        voronoiTabWidget->setCurrentPage(0);
        layerNameLineEdit->setFocus();
		return;
	}

    std::string layerLinesName;
    if(generateLinesCheckBox->isChecked())
    {
        layerLinesName = layerLinesLineEdit->text().ascii();
        if(layerLinesName.empty())
	    {
		    QMessageBox::information(this, tr("Information"), tr("Please, define a name to Layer of Lines."));
            voronoiTabWidget->setCurrentPage(1);
            layerLinesLineEdit->setFocus();
		    return;
	    }
    }

    if(!isLayerNameValid(layerName))
    {
        voronoiTabWidget->setCurrentPage(0);
        layerNameLineEdit->setFocus();
        return;
    }

    if(!isLayerNameValid(layerLinesName))
    {
        voronoiTabWidget->setCurrentPage(1);
        layerLinesLineEdit->setFocus();
        return;
    }

    if(layerName == layerLinesName)
    {
        QMessageBox::information(this, tr("Information"), tr("Please, define names differents to Layer result and Layer of Lines."));
	    return;
    }

	TeDatabase* db = plugin_params_->getCurrentDatabasePtr();
    TeTheme* theme = getTheme(themeComboBox->currentText().latin1());
	if(theme == 0)
	{
		QMessageBox::critical(this, tr("Error"), tr("Error getting the input Theme."));
		return;
	}
    
    TePrecision::instance().setPrecision(TeGetPrecision(theme->layer()->projection()));
    
    TeTheme *themeDelimiter = getTheme(boxComboBox->currentText().latin1());
    if(themeDelimiter == 0)
    {
        QMessageBox::critical(this, tr("Error"), tr("Error getting the delimiter Layer."));
		return;
    }

    // Verifies is the box chosen is valid
    TeBox b = themeDelimiter->layer()->box();
    TeProjection* projFrom = themeDelimiter->layer()->projection();
    TeProjection* projTo = theme->layer()->projection();
    if(!((*projFrom) == (*projTo))) // need remap?
        b = TeRemapBox(b, projFrom, projTo);

    TeBox& inputBox = theme->layer()->box();
    if(!TeIntersects(b, inputBox))
    {
        QMessageBox::information(this, tr("Information"), tr("The box chosen do not intercepts the input Theme. Please, try another."));
        voronoiTabWidget->setCurrentPage(1);
        boxComboBox->setFocus();
        return;
    }
    
    //preparing to read the layer
    bool loadAllAttributes=false;
    if (diagramType==MWVoronoi) loadAllAttributes = true;
    bool loadGeometries = true;
    TeQuerierParams querierParams(loadGeometries, loadAllAttributes);
    querierParams.setParams(theme->layer());
    TeQuerier  querier(querierParams);
    querier.loadInstances();
    //finding weight's attribute
    TeAttributeList attrList = querier.getAttrList();
    int weightAttrN=0;
    if (diagramType==MWVoronoi) {
        for (std::vector<TeAttribute>::iterator i=attrList.begin(); i!=attrList.end();++i) {
            if (weightComboBox->currentText()==i->rep_.name_) {
                break;
            }
            weightAttrN++;
        }    
    }
    int n=querier.numElemInstances();

    if(n==0)
    {
        QMessageBox::critical(this, tr("Error"), tr("Error getting the points of input Theme."));
        return;
    }

    TeWaitCursor wait;

    // Converts x,y to a float array in order to pass to VoronoiDiagramGenerator class
    float* x = new float[n];
	float* y = new float[n];
    //pointers for weighted voronoi
    float* w;
    int numPoints;
    w= new float[n];
    numPoints = 0;
    TeSTInstance sti;
    string peso;
    //TePoint pointBefore(0,0);
    while(querier.fetchInstance(sti)) { // for each point
        // Stores on float array
        if(sti.hasPoints())
            {
                TePointSet pointSet;
                //reading geometry
                sti.getGeometry(pointSet);
                x[numPoints] = pointSet[0].location().x();
                y[numPoints] = pointSet[0].location().y();
    
                //reading weight
                if (diagramType==MWVoronoi) {
                    stringstream ss;
                    sti.getPropertyValue(peso,weightAttrN);
                    ss<<peso;
                    ss>>w[numPoints];
                }                    
                numPoints++;
            }