package eu.eudat.logic.managers;

import eu.eudat.data.entities.DMP;
import eu.eudat.depositinterface.models.DMPDepositModel;
import eu.eudat.depositinterface.repository.RepositoryDeposit;
import eu.eudat.depositinterface.repository.RepositoryDepositConfiguration;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.logic.security.repositorydeposit.mapper.DMPToDepositMapper;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.pdf.PDFUtils;
import eu.eudat.models.data.doi.DepositRequest;
import eu.eudat.models.data.doi.Doi;
import eu.eudat.models.data.doi.RepositoryConfig;
import eu.eudat.models.data.security.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
public class DepositManager {
    private static final Logger logger = LoggerFactory.getLogger(DepositManager.class);

    private List<RepositoryDeposit> repositories;
    private DataManagementPlanManager dataManagementPlanManager;

    @Autowired
    public DepositManager(List<RepositoryDeposit> repositories, DataManagementPlanManager dataManagementPlanManager){
        this.repositories = repositories;
        this.dataManagementPlanManager = dataManagementPlanManager;
    }

    public List<RepositoryConfig> getAvailableRepos() {
        List<RepositoryConfig> reposConfigModel = new ArrayList<>();
        for (RepositoryDeposit r: this.repositories) {
            RepositoryConfig repoModel = new RepositoryConfig();
            reposConfigModel.add(repoModel.toModel(r.getConfiguration()));
        }
        return reposConfigModel;
    }

    public String authenticate(String id, String code) {
        Optional<RepositoryDeposit> repo = repositories.stream().filter(x -> x.getConfiguration().getRepositoryId().equals(id)).findFirst();
        return repo.map(repositoryDeposit -> repositoryDeposit.authenticate(code)).orElse(null);
    }

    public Doi deposit(DepositRequest depositRequest, Principal principal) throws Exception {
        return this.dataManagementPlanManager.createDoi(depositRequest, principal);
    }
}
