package fr.alecharp.picshare.service;

import fr.alecharp.picshare.domain.Event;
import fr.alecharp.picshare.domain.Picture;
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;
import java.util.Set;

/**
 * @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));
    }

    public Optional<Event> attachPictures(String id, Set<Picture> pictures) {
        Optional<Event> event = get(id);
        if (!event.isPresent()) return event;
        return save(event.get().pictures(pictures));
    }
}

@@ -317,16 +317,43 @@
 .Files;%0A
+import java.nio.file.Path;%0A
 import j
@@ -372,16 +372,16 @@
 .Paths;%0A
-
 import j
@@ -420,16 +420,85 @@
 til.Set;
+%0Aimport java.util.zip.ZipEntry;%0Aimport java.util.zip.ZipOutputStream;
 %0A%0A/**%0A *
@@ -1553,51 +1553,963 @@
     
-return save(event.get().pictures(pictures))
+Optional%3CEvent%3E save = save(event.get().pictures(pictures));%0A        if (save.isPresent()) %7B%0A            try %7B%0A                createZip(save.get());%0A            %7D catch (IOException e) %7B%0A                // TODO log%0A                e.printStackTrace();%0A            %7D%0A        %7D%0A        return save;%0A    %7D%0A%0A    private void createZip(Event event) throws IOException %7B%0A        Path dest = Paths.get(storage, event.id(), %22event.zip%22);%0A        try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(dest))) %7B%0A            for (Picture picture : event.pictures()) %7B%0A                zip.putNextEntry(new ZipEntry(picture.title()));%0A                Files.copy(Paths.get(picture.path()), zip);%0A                zip.closeEntry();%0A            %7D%0A        %7D%0A    %7D%0A%0A    public Path getZip(String id) throws IOException %7B%0A        Path path = Paths.get(storage, id, %22event.zip%22);%0A        if (Files.notExists(path)) createZip(get(id).get());%0A        return path
 ;%0A  

Create a zip of the event