package com.iqser.red.service.persistence.management.v1.processor.dataexchange.zipreaders;

import com.iqser.red.service.persistence.management.v1.processor.dataexchange.FileExchangeNames;
import com.iqser.red.service.persistence.management.v1.processor.dataexchange.models.DatasetExchangeImportModel;

import lombok.AccessLevel;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;

@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class DatasetExchangeArchiveReader {

    DossierTemplateArchiveReader dossierTemplateArchiveReader;
    DatasetExchangeImportModel datasetExchangeImportModel;


    public DatasetExchangeArchiveReader(String userId) {

        dossierTemplateArchiveReader = new DossierTemplateArchiveReader(userId, null, false);
        datasetExchangeImportModel = new DatasetExchangeImportModel();
    }


    public DatasetExchangeImportModel getDatasetExchangeImportModel() {

        datasetExchangeImportModel.setImportTemplateResult(dossierTemplateArchiveReader.buildResult());
        return datasetExchangeImportModel;
    }


    @SneakyThrows
    public void handleZipEntryData(ZipEntryData zipEntryData) {

        if (zipEntryData.getBaseFolder().equals(FileExchangeNames.TEMPLATE_FOLDER)) {
            dossierTemplateArchiveReader.handleZipEntryData(zipEntryData);
        } else if (zipEntryData.getDepth() >= 1) { // in dossier folders

            String dossierName = zipEntryData.getBaseFolder().replaceAll("\\s*\\([1-9]+\\)", "");
            String fileName = zipEntryData.getFileName();
            if (!fileName.endsWith(".pdf")) {
                return;
            }

            var dossier = datasetExchangeImportModel.getOrCreateDossier(dossierName);
            dossier.getFiles().add(new DatasetExchangeImportModel.File(fileName, zipEntryData.data()));
        }

    }

}
