package io.toro.workshop.blog;

import io.toro.workshop.blog.event.BlogUpdatedEvent;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
@RequestMapping( value = "api/blogs" )
public class BlogApiController {

    private final BlogService blogService;
    private final ApplicationEventPublisher eventPublisher;

    @Autowired
    BlogApiController( BlogService blogService, ApplicationEventPublisher publisher ) {
        this.blogService = blogService;
        this.eventPublisher = publisher;
    }

    @RequestMapping( method = RequestMethod.GET )
    ResponseEntity<List<Blog>> getBlogs() {
        List<Blog> blogs = blogService.findBlogs();

        return ResponseEntity.ok( blogs );
    }

    @RequestMapping( value = "{id}", method = RequestMethod.GET )
    ResponseEntity<Blog> getBlog( @PathVariable Long id ) {
        Blog blog = blogService.findBlog( id );

        return ResponseEntity.ok( blog );
    }

    @RequestMapping( method = RequestMethod.POST )
    ResponseEntity<Blog> saveBlog( @RequestBody Blog blog ) {
        blog = blogService.saveBlog( blog );
        eventPublisher.publishEvent( new BlogUpdatedEvent( blog ) );

        return ResponseEntity.ok( blog );
    }

    @RequestMapping( value = "{id}", method = RequestMethod.DELETE )
    ResponseEntity<Void> deleteblog( @PathVariable Long id ) {
        blogService.deleteBlogById( id );

        return ResponseEntity.noContent().build();
    }

}

@@ -643,16 +643,95 @@
 troller;
+%0Aimport org.springframework.web.util.UriComponentsBuilder;%0Aimport java.net.URI;
 %0A%0A@Cross
@@ -1650,21 +1650,47 @@
 log blog
+, UriComponentsBuilder ucb
  ) %7B%0A
-
         
@@ -1792,24 +1792,132 @@
  blog ) );%0A%0A
+        URI locationURI = ucb.path( %22/api/blogs/%22 ).path( String.valueOf( blog.getId() ) ).build().toUri();%0A
         retu
@@ -1926,34 +1926,59 @@
  ResponseEntity.
-ok
+created( locationURI ).body
 ( blog );%0A    %7D%0A

refactor save endpoint to conform standard