package com.iqser.red.service.peristence.v1.server.utils;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.SplittableRandom;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;

import com.iqser.red.service.persistence.management.v1.processor.utils.FileSystemBackedArchiver;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileSystemBackArchiverTest {

    @Test
    @SneakyThrows
    public void testFileSystemBackedArchiver() {

        try (var fsba = new FileSystemBackedArchiver()) {

            SplittableRandom sr = new SplittableRandom();

            var data = sr.doubles().limit(1024 * 1024).toArray();
            for (int i = 0; i < 10; i++) {
                log.info("At entry: {}, using {}MB of memory", i, (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024));

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(data);
                byte[] bytes = bos.toByteArray();
                bos.close();
                var entry = new FileSystemBackedArchiver.ArchiveModel("folder-" + i, "file-" + i, bytes);
                fsba.addEntry(entry);
            }

            File f = File.createTempFile("test", ".zip");

            var contentSize = fsba.getContentLength();

            try (FileOutputStream fos = new FileOutputStream(f)) {
                IOUtils.copy(fsba.toInputStream(), fos);
                log.info("File: {}", f.getAbsolutePath());

                assertThat(f.length()).isEqualTo(contentSize);
            }

            log.info("Total File Size: {}MB", f.length() / (1024 * 1024));

        }
    }

}
