package com.workfusion.odf.impl.converter.extractor.zip;

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

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;

import com.workfusion.odf.impl.converter.extractor.AbstractRecursiveExtractor;
import com.workfusion.odf.impl.converter.extractor.DataWrapper;

public class RecursiveZipExtractor extends AbstractRecursiveExtractor {
    private static final String ZIP_SUFFIXES[] = {"zip"};

    /**
     * Constructor.
     *
     * @param logger
     */
    public RecursiveZipExtractor(final Logger logger) {
    	super(logger);
    }

    @Override
    public String[] getExtensions() {
        return ZIP_SUFFIXES;
    }

    @Override
    protected List<DataWrapper> extract(final DataWrapper archive) {
        try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(archive.getData()))) {
            final List<DataWrapper> result = new ArrayList<>();

            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (entryIsNotDirectory(entry)) {
                    final byte[] bytesOfEntry = IOUtils.toByteArray(zipInputStream);
                    final String entryName = entry.getName().replace("/", "_"); //file has its parent folder prefixes separated with '/'
                    result.add(new DataWrapper(bytesOfEntry, entryName, null, null));
                }
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private boolean entryIsNotDirectory(final ZipEntry entry) {
        return !entry.isDirectory();
    }
}
