package org.gcube.application.geoportal.utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gcube.application.geoportal.model.MOSI;
import org.gcube.application.geoportal.model.db.PostgisTable.Field;
import org.gcube.application.geoportal.model.fault.InvalidRecordException;

import lombok.extern.slf4j.Slf4j;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.features.user.FeatureResultSet;
import mil.nga.geopackage.manager.GeoPackageManager;

@Slf4j
public class GpkgUtils {

		
	public static GeoPackage open(File gpkg) {
		return  GeoPackageManager.open(gpkg);
	}
	
	public static Map<String,Object> rowAsMap(FeatureResultSet rs,List<Field> targetSchema) throws InvalidRecordException{
		HashMap<String,Object> row= new HashMap<String, Object>();
		for(int i=0;i<targetSchema.size();i++) {
			Field current=targetSchema.get(i);

			switch(current.getType()){
			case FLOAT : {row.put(current.getName(), rs.getFloat(i));
			break;}
			case INT : {row.put(current.getName(), rs.getInt(i));
			break;}
			case TEXT : {row.put(current.getName(), rs.getString(i));
			break;}
			case GEOMETRY : {
				try{
					row.put(current.getName(), rs.getGeometry().getWkbBytes());
					}catch(Throwable t) {
						throw new InvalidRecordException("Unable to read Geom ",t);
					}
				break;}
			}
		}
		return row;
	}
	
	//TODO
//	public static Map<String,MOSI> loadMosiFromTable(File gpkgFile, String table){
//		log.info("Loading MOSIs from "+table+" in "+gpkgFile.getAbsoluteFile());
//		GeoPackage gpkg=open(gpkgFile);
//		gpkg.getFeatureDao(table);	
//	}
}
