package de.tobias.playwall.controller;

import de.tobias.playwall.model.Plugin;
import de.tobias.playwall.service.ArtifactoryClient;
import de.tobias.playwall.service.PluginService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.util.List;

@RestController
@RequestMapping("/plugins")
@AllArgsConstructor
public class PluginController
{
	private final PluginService service;
	private final ArtifactoryClient artifactoryClient;

	@GetMapping
	List<Plugin> getAllPlugins()
	{
		return service.getAllPlugins();
	}

	@GetMapping("/{id}")
	Plugin getPlugin(@PathVariable Integer id)
	{
		return service.getPlugin(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
	}

	@GetMapping("/raw/{id}")
	Mono<byte[]> getPluginExecutable(@PathVariable Integer id)
	{
		final Plugin plugin = service.getPlugin(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
		return artifactoryClient.downloadArtifact(plugin);
	}
}