package org.gcube.application.geoportal.db;

import java.io.File;
import java.io.FileFilter;
import java.util.Map;

import org.gcube.application.geoportal.PostgisTableFactory;
import org.gcube.application.geoportal.model.db.DBConstants;
import org.gcube.application.geoportal.model.db.DatabaseConnection;
import org.gcube.application.geoportal.model.db.PostgisTable;
import org.gcube.application.geoportal.model.db.PostgisTable.GeometryType;
import org.gcube.application.geoportal.storage.PostgisDBManager;
import org.gcube.application.geoportal.storage.PostgisDBManagerI;
import org.gcube.application.geoportal.utils.CSV;
import org.gcube.application.geoportal.utils.Files;
import org.gcube.application.geoportal.utils.MainUtils;

public class PostgisTests {

	private static final String USAGE="<OPTIONS>"			
			+ "options : "
			+ "--DBUSER"
			+ "--DBPWD"
			+ "--DBURL"
			+ "--COMMIT"
			+ "--CSV_PATH";
			
	
	public static void main(String[] args) throws Throwable {
		if(args.length<1) {
			System.out.println(USAGE);
			System.exit(0);
		}
		

		Map<String,String> options=MainUtils.asMap(args);
		System.out.println("Options : "+options);
		
		DatabaseConnection postgisConnection= new DatabaseConnection(MainUtils.getMandatory("DBUSER",options),
				MainUtils.getMandatory("DBPWD",options), MainUtils.getMandatory("DBURL",options));
		
		postgisConnection.setAutocommit(false);
		
		PostgisDBManager.init(postgisConnection);
		
		
		PostgisDBManagerI db=PostgisDBManager.get();
		
		
		System.out.println("Current centroids extent");
		
		db.create(DBConstants.Concessioni.CENTROIDS);
		System.out.println(db.evaluateBoundingBox(DBConstants.Concessioni.CENTROIDS));
		PostgisTableFactory f=new PostgisTableFactory(db);
		
		File csvFolder=null;
		try {
			csvFolder=new File(MainUtils.getMandatory("CSV_PATH", options));
		}catch(RuntimeException e) {
			System.out.println("USING DEFAULT CSVs..");
			csvFolder=Files.getFileFromResources("csv");
		}
		
		for(File csvFile:csvFolder.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				if(pathname.isDirectory()) return false;
				return pathname.getName().endsWith(".csv");
			}
		})){

			try {
				PostgisTable table =f.fromCSV(csvFile.getAbsolutePath());
				
				System.out.println("Created table : "+table);
				db.deleteTable(table.getTablename());
				db.commit();
				System.out.println("Deleted");
			}catch(Throwable t) {
				if(!csvFile.getName().contains("wrong")) 				
					throw t;
				else {
					System.out.println(" File was corrupted as expected");
					t.printStackTrace(System.out);
				}
			}
			
		}
	}

}
