package org.gcube.application.geoportal.utils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.gcube.application.geoportal.model.db.DBInteractionException;
import org.gcube.application.geoportal.model.db.PostgisTable;
import org.gcube.application.geoportal.model.db.PostgisTable.GeometryType;
import org.gcube.application.geoportal.model.fault.DataParsingException;
import org.gcube.application.geoportal.storage.PostgisDBManager;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CSV {

	public static final CSVParser fromPath(String csvFile) throws FileNotFoundException, IOException {
		return CSVParser.parse(new FileReader(csvFile), CSVFormat.DEFAULT.withFirstRecordAsHeader()) ;
	}
	
	
	
	
	
//	public static final PostgisTable updateTable(PostgisTable table, String csvPath, PostgisDBManager db, boolean clean) throws SQLException, IOException, DBInteractionException, DataParsingException {
//		CSVParser parser=null;
//		try {
//			log.debug("Updateing table "+table.getTablename()+" with "+csvPath);
//			parser=fromPath(csvPath);
//			if(clean) {
//				log.debug("Truncating existing");
//				db.truncate(table.getTablename());				
//			}
//			return persist(parser,table,db);
//			
//			
//		}finally {
//			if(parser!=null&&!parser.isClosed())
//				parser.close();
//		}
//	}
	
	
	
//	public static final PostgisTable persistCSVLayer(String csvFile,GeometryType type, PostgisDBManager db) throws FileNotFoundException, IOException, SQLException, DBInteractionException, DataParsingException {
//		CSVParser parser=null;
//		try {
//			parser=fromPath(csvFile);
//			PostgisTable toPersist= PostgisTable.fromCSVHeaders(parser.getHeaderNames(), type);
//			
//			toPersist.setTablename(Files.getName(csvFile)+"_"+toPersist.getTablename());
//			
//			
//			
//			return persist(parser,toPersist,db);
//		}finally {
//			if(parser!=null&&!parser.isClosed())
//				parser.close();
//		}
//	}

	
	public static GeometryType getTypeFromPath(String csv) {
		GeometryType type=GeometryType.POINT;			
		if(csv.contains("linee"))
			type=GeometryType.LINE;
		else if(csv.contains("poligoni"))
			type=GeometryType.POLYGON;
		
		return type;
	}
	
}
