package com.iqser.red.service.persistence.management.v1.processor.dev;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.service.DossierTemplateImportService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.DossierTemplateRepository;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.importexport.ImportDossierTemplateRequest;
import com.knecon.fforesight.tenantcommons.TenantContext;

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

@Slf4j
@Service
@Profile("dev")
@RequiredArgsConstructor
public class DevDataProvider {

    private final DossierTemplateImportService dossierTemplateImportService;

    private final DossierTemplateRepository dossierTemplateRepository;


    public void importDossierTemplatesToTenant(String tenantId) {

        TenantContext.setTenantId(tenantId);
        if (dossierTemplateRepository.count() == 0) {
            executeImport();
        }
        TenantContext.clear();
    }


    public byte[] pack(String sourceDirPath) throws IOException {

        var bos = new ByteArrayOutputStream();
        var p = Paths.get(sourceDirPath);
        try (ZipOutputStream zs = new ZipOutputStream(bos)) {
            Stream<Path> paths = Files.walk(p);
            {
                paths.filter(path -> !Files.isDirectory(path)).forEach(path -> {
                    ZipEntry zipEntry = new ZipEntry(p.relativize(path).toString());
                    try {
                        zs.putNextEntry(zipEntry);
                        Files.copy(path, zs);
                        zs.closeEntry();
                    } catch (IOException e) {
                        System.err.println(e);
                    }
                });
            }
        }

        return bos.toByteArray();

    }


    @SneakyThrows
    private void executeImport() {

        var importDir = new File("/Users/timobejan/work/dossier-templates-v2/dev");

        for (var file : importDir.listFiles()) {
            if (file.isDirectory()) {
                var archive = pack(file.getAbsolutePath());
                log.info("Importing file: " + file.getName() + " " + " with size: " + archive.length);
                var request = new ImportDossierTemplateRequest();
                request.setArchive(archive);
                request.setUpdateExistingDossierTemplate(false);
                request.setUserId("system");
                dossierTemplateImportService.importDossierTemplate(request);
            }
        }
    }

}
