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

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

import java.io.IOException;
import java.util.Optional;

@Service
public class DocumentService {
    private DocumentRepository documentRepository;

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

    public Optional<Document> add(MultipartFile file) {
        return Optional.of(Document.builder()
                        .fileName(file.getOriginalFilename())
                        .fileType(file.getContentType())
                        .bytes(getBytes(file))
                        .build())
                .map(document->documentRepository.save(document));
    }

    public Optional<Document> readFile(Long id){
        return documentRepository.findById(id);
    }

    private byte[] getBytes(MultipartFile file) {
        try{
            return file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
