package com.capgemini.reports.reports.output;


import com.capgemini.framework.teamcenter.exceptions.KurtException;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

public class ZipReport implements ReportOutput {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZipReport.class);

    private final String zipFilePath;
    private final List<File> filesToCompress;

    public ZipReport(final String zipFilePath, final List<File> filesToCompress) {
        this.zipFilePath = zipFilePath;
        this.filesToCompress = filesToCompress;
    }

    @Override
    public ZipFile print() throws KurtException {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            ZipParameters parameters = zipParameters();
            addFilesToZip(zipFile, parameters);
            return zipFile;
        } catch (ZipException e) {
            throw new KurtException(e.getMessage(), e);
        }
    }

    private ZipParameters zipParameters() {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        return parameters;
    }

    private void addFilesToZip(ZipFile zipFile, ZipParameters parameters) throws ZipException {
        for (File file : filesToCompress) {
            zipFile.addFile(file, parameters);
            if (file.delete()) {
                LOGGER.debug("Archive file {} deleted.", file.getName());
            }
        }
    }
}
