package es.uv.garcosda.controllers;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import es.uv.garcosda.domain.Document;
import es.uv.garcosda.services.NewsService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/api/v1/news")
@CrossOrigin
public class NewsController {
	
	@Autowired
	private NewsService ns;
	
	@GetMapping("{id}")
    public Mono<Document> getOne(@PathVariable("id") Integer id) {
        return this.ns.findById(id);
    }
	
	@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public Flux<Document> getAll() {
		return this.ns.findAll().delayElements(Duration.ofMillis(500));
	}
	
	@GetMapping("publisher/{publisher}")
    public Flux<Document> getByPublisher(@PathVariable("publisher") String publisher) {
        return this.ns.findByPublisher(publisher).delayElements(Duration.ofMillis(500));
    }
	
	@GetMapping("author/{author}")
    public Flux<Document> getByAuthor(@PathVariable("author") String author) {
        return this.ns.findByAuthor(author).delayElements(Duration.ofMillis(500));
    }
	
	@PostMapping()
	public Mono<Document> insert(@RequestBody Document n){
		n.setDateAdd(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
		return this.ns.insert(n);	
	}
	
	@PutMapping()
	public Mono<Document> update(@RequestBody Document n){
		return this.ns.update(n);
	}
	
	@DeleteMapping("{id}")
	public Mono<Integer> delete(@PathVariable("id") Integer id){
		return this.ns.deleteById(id).then(Mono.just(id));		
	}
	
	@GetMapping(value="/authors")
    public Flux<String> getAuthors() {
		return this.ns.findAuthors()
					  .map(p -> p.concat("\n"));
    }

    @GetMapping("/publishers")
    public Flux<String> getPublishers() {
    	return this.ns.findPublishers()
				  .map(p -> p.concat("\n"));
    } 
	
}
