package de.avatic.taricdb.helper.zip;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.avatic.taricdb.helper.file.InMemFile;
import de.avatic.taricdb.service.SetupStatusService;


@Component
public class Unzipper {
	
	@Autowired
	private SetupStatusService statusService;
	 
	Logger log = LoggerFactory.getLogger(Unzipper.class);

	public List<InMemFile> unzip(byte[] zipFile) throws IOException {
		List<InMemFile> files = new ArrayList<>();
		ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(zipFile));
		ZipEntry entry;
		
	    while ((entry = zipStream.getNextEntry()) != null) {
			if (!entry.isDirectory()) {
				files.add(new InMemFile(entry.getName(), readFileContent(zipStream, entry)));
			}
	        zipStream.closeEntry();
	        log.info("Unzip done: " + entry.getName());
			statusService.setStatus(0, "unzipping ... " + entry.getName(), true, null);
	    }
	    
	    return files;
	}
	
	private byte[] readFileContent(InputStream zipStream, ZipEntry entry) throws IOException {
		int totalRead = 0;
		List<ByteArrayWrapper> content = new ArrayList<>();
	
	    while (zipStream.available() > 0) {
	        byte[] bytes = new byte[10240];	    	
	        int read = zipStream.read(bytes, 0, bytes.length);
	        
			if (read == -1) {
				break;
			}
	        
	        content.add(new ByteArrayWrapper(Arrays.copyOf(bytes, read)));
	        totalRead += read;
	    }
	    
	    return content.stream().reduce(new ByteArrayWrapper(new byte[0]), ByteArrayWrapper::combine).getBytes();
        	
	}


}
