package com.kamco.cd.kamcoback.common.utils.zip;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZipUtils {

  private final List<ZipEntryProcessor> processors;

  public ZipUtils(List<ZipEntryProcessor> processors) {
    this.processors = processors;
  }

  public void processZip(InputStream zipStream) throws IOException {
    try (ZipInputStream zis = new ZipInputStream(zipStream)) {

      ZipEntry entry;
      while ((entry = zis.getNextEntry()) != null) {

        if (entry.isDirectory()) {
          continue;
        }

        String fileName = entry.getName();
        processors.stream()
            .filter(p -> p.supports(fileName))
            .findFirst()
            .ifPresent(
                processor -> {
                  try {
                    processor.process(fileName, zis);
                  } catch (IOException ioe) {
                    throw new UncheckedIOException(ioe);
                  }
                });

        zis.closeEntry();
      }
    }
  }
}
