package edu.uprm.walsaip.vte.core.loader.image;


import static java.lang.System.out;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import edu.uprm.walsaip.vte.core.datatypes.terrain.VTEInfo;
import edu.uprm.walsaip.vte.core.datatypes.terrain.TextureData;
import edu.uprm.walsaip.vte.core.exceptions.InvalidFileException;
import edu.uprm.walsaip.vte.core.loader.FileLoaderInfo;
import edu.uprm.walsaip.vte.core.loader.envi.EnviFileLoader;
import edu.uprm.walsaip.vte.core.loader.envi.EnviHeader;
import edu.uprm.walsaip.vte.core.loader.envi.MapInfo;
import edu.uprm.walsaip.vte.core.util.FileUtils;
import edu.uprm.walsaip.vte.core.util.file.FileReaderUtil;


public class EnviImageFileLoader extends EnviFileLoader implements ImageFileLoader{
	
	public static final String ID = EnviImageFileLoader.class.getSimpleName();	
	public static final String Type = ImageFileLoader.ID;
	
public static final FileLoaderInfo<EnviImageFileLoader> MODULE_INFO = new FileLoaderInfo<EnviImageFileLoader>() {
		
		protected void setInfo() {
			name = EnviImageFileLoader.ID;
			description = "ENVI image file";
			moduleClass = EnviImageFileLoader.class;
			extensionList = EnviFileLoader.extensionList;
			supported = true;
		}
	};
	
	public void read(TextureData data, VTEInfo info,File file) {

		out.printf("Reading terrain file...");

		EnviHeader header = null;
		MapInfo mapInfo = null;
		File dataFile = null;

		
		
		FileReaderUtil fileReader = null;
		try {

			header = EnviHeader.readHeaderFile(file);
			mapInfo = header.getMapInfo();
			
			dataFile = new File(header.getDataFilename());

			fileReader = FileUtils.getFileReaderUtil(dataFile);
			


			data.setGridSpacingX((float) mapInfo.getPixelSizeX());
			data.setGridSpacingY((float) mapInfo.getPixelSizeX());
			data.setFile(file);

			String fileFormat = header.getInterleave();

			if (fileFormat.equals("bil")) {
				readBIL(header, fileReader, data);
			} else if (fileFormat.equals("bip")) {
				readBIP(header, fileReader, data);
			} else if (fileFormat.equals("bsq")) {
				readBSQ(header, fileReader, data);
			}

			fileReader.close();

		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fileReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		out.println("done");
		
	}
}
