package fr.alecharp.picshare.service;

import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.repository.EventRepository;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;

/**
 * @author Adrien Lecharpentier
 */
@Singleton
public class EventService {
    private final EventRepository eventRepository;
    private final String storage;

    @Inject
    public EventService(EventRepository eventRepository, @Named("storageLocation") String storage) {
        this.eventRepository = eventRepository;
        this.storage = storage;
    }

    public Optional<Event> save(Event event) {
        try {
            event = eventRepository.save(event);
            Files.createDirectories(Paths.get(storage, event.id(), ".thumb"));
            return Optional.ofNullable(event);
        } catch (IOException e) {
            return Optional.empty();
        }
    }

    public void remove(String id) {
        eventRepository.delete(id);
    }

    public Optional<Event> get(String id) {
        return Optional.ofNullable(eventRepository.findById(id));
    }
}

@@ -74,16 +74,60 @@
 .Event;%0A
+import fr.alecharp.picshare.domain.Picture;%0A
 import f
@@ -371,16 +371,38 @@
 ptional;
+%0Aimport java.util.Set;
 %0A%0A/**%0A *
@@ -1278,11 +1278,236 @@
 );%0A    %7D
+%0A%0A    public Optional%3CEvent%3E attachPictures(String id, Set%3CPicture%3E pictures) %7B%0A        Optional%3CEvent%3E event = get(id);%0A        if (!event.isPresent()) return event;%0A        return save(event.get().pictures(pictures));%0A    %7D
 %0A%7D%0A

Update event service to attach pictures to event