package com.k_int.aggregator.dpp.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.k_int.peoples_record.repository.Repository;
import com.k_int.peoples_record.repository.StoreResult;

public class UploadUtils {

	private static Log log = LogFactory.getLog(UploadUtils.class);

	
	public static ArrayList<StoreResult> uploadAndStore(Repository repository, File file, String contentType, String filename, Long resourceId) {
		log.debug("uploadAndStore called");
		ArrayList<StoreResult> returnValue = new ArrayList<StoreResult>();

		try {
			InputStream mediaIs = file.toURI().toURL().openStream();
			if ( mediaIs != null ) {
				ByteArrayOutputStream mediaBaos = new ByteArrayOutputStream();
				int mediaB = mediaIs.read();
				while ( mediaB != -1 ) {
					mediaBaos.write(mediaB);
					mediaB = mediaIs.read();
				}
				byte[] mediaFileAsArray = mediaBaos.toByteArray();
				mediaBaos.close();
				mediaIs.close();
				mediaIs = null;
				mediaBaos = null;
				
				// Byte array created - now pass it to the repository
				returnValue.addAll(repository.storeObject(mediaFileAsArray, contentType, resourceId, filename));
				log.debug("file: " + filename + " stored in the repository...");
				log.debug("returnValue.size = " + returnValue.size());
				for(StoreResult res: returnValue) {
					log.debug("this result: " + res.toString());
				}
			}
		} catch ( MalformedURLException mue ) {
			log.error("MalformedURLException thrown when reading in the uploaded file: " + mue.getMessage());
		} catch ( IOException ioe ) {
			log.error("IOException thrown when reading in the uploaded file: " + ioe.getMessage());
		}

                log.debug("Returning from uploadAndStore");
		return returnValue;
	}
	
	
	public static void unpack(byte[] zip, String pathToTempDir) throws IOException {
		
		final int BUFFER = 2048;
		
		ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zip));
		ZipEntry entry;
		
		// Loop through everything in the archive writing it to disk
		while((entry = zis.getNextEntry()) != null ) {
			OutputStream out = null;
			String name = entry.getName();
			log.debug("About to extract " + name);
			
			File f = new File(pathToTempDir, name);
			out = new FileOutputStream(f);
			
			int count;
			byte data[] = new byte[BUFFER];
			while ((count = zis.read(data, 0, BUFFER)) != -1 ) {
				out.write(data, 0, count);
			}
			
			out.close();
		}
		
		zis.close();

		return;
	}

}
