package edu.prlab.tyler.iotgateway.cloud.services;

import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.repositories.DocumentRepository;
import edu.prlab.tyler.iotgateway.cloud.services.storage.StorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Optional;

@Service
public class DocumentService {
    private DocumentRepository documentRepository;
    private StorageService storageService;

    public DocumentService(DocumentRepository repository,
                           StorageService storageService) {
        this.documentRepository = repository;
        this.storageService = storageService;
    }

    public Optional<Document> add(MultipartFile file) {
        return Optional.ofNullable(storageService.store(file))
                .map(filename -> Document.builder()
                        .fileName(filename)
                        .build())
                .map(document->documentRepository.save(document));
    }
}
