/*
 * Copyright 2015 EuregJUG.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.euregjug.site.web;

import eu.euregjug.site.events.EventRepository;
import eu.euregjug.site.events.RegistrationService;
import eu.euregjug.site.links.LinkEntity;
import eu.euregjug.site.links.LinkRepository;
import eu.euregjug.site.posts.Post;
import eu.euregjug.site.posts.PostEntity;
import eu.euregjug.site.posts.PostRenderingService;
import eu.euregjug.site.posts.PostRepository;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import static java.util.stream.Collectors.groupingBy;

/**
 * @author Michael J. Simons, 2015-12-27
 */
@Controller
class IndexController {
    private final EventRepository eventRepository;
    
    private final RegistrationService registrationService;
    
    private final LinkRepository linkRepository;

    private final PostRepository postRepository;
    
    private final PostRenderingService postRenderingService;
    
    @Autowired
    public IndexController(
	    EventRepository eventRepository, 
	    RegistrationService registrationService, 
	    LinkRepository linkRepository, 
	    PostRepository postRepository, 
	    PostRenderingService postRenderingService
    ) {
	this.eventRepository = eventRepository;
	this.registrationService = registrationService;
	this.linkRepository = linkRepository;	
	this.postRepository = postRepository;
	this.postRenderingService = postRenderingService;	
    }
    
    @RequestMapping({"", "/", "/feed"})
    public String index(
	    final @RequestParam(required = false, defaultValue = "0") Integer page,
	    final Model model
    ) {
	model
		.addAttribute("upcomingEvents", this.eventRepository.findUpcomingEvents())
		.addAttribute("links", this.linkRepository.findAllByOrderByTypeAscSortColAscTitleAsc().stream().collect(groupingBy(LinkEntity::getType)))
		.addAttribute("posts", this.postRepository.findAll(new PageRequest(page, 5, Direction.DESC, "publishedOn", "createdAt")).map(postRenderingService::render))	
		;
	return "index";
    }   
    
    @RequestMapping({
	"/{year:\\d+}/{month:\\d+}/{day:\\d+}/{slug}",
	"/posts/{year:\\d+}-{month:\\d+}-{day:\\d+}-{slug}"
    })
    public String post(
	    final @PathVariable Integer year,
	    final @PathVariable Integer month,
	    final @PathVariable Integer day,
	    final @PathVariable String slug,
	    final Model model
    ) {

	String rv = "redirect:/";
	try {
	    final Date publishedOn = Date.from(LocalDate.of(year, month, day).atStartOfDay(ZoneId.systemDefault()).toInstant());	    
	    final Optional<PostEntity> post = this.postRepository.findByPublishedOnAndSlug(publishedOn, slug);
	    model
		    .addAttribute("previousPost", post.flatMap(this.postRepository::getPrevious))
		    .addAttribute("post", post.map(postRenderingService::render).get())
		    .addAttribute("nextPost", post.flatMap(this.postRepository::getNext))
		    ;
	    rv = "post";

	} catch (DateTimeException | NoSuchElementException e) {
	}
	return rv;
    }
    
    @RequestMapping({"/archive", "/archives"})
    public String archive(final Model model) {
	model.addAttribute("posts", this.postRepository.findAll().stream().map(Post::new).collect(Collectors.groupingBy(post -> post.getPublishedOn().withDayOfMonth(1))));
	return "archive";
    }
}
@@ -1090,24 +1090,47 @@
 .util.Date;%0A
+import java.util.List;%0A
 import java.
@@ -1202,33 +1202,23 @@
 va.util.
-stream.Collectors
+TreeMap
 ;%0Aimport
@@ -1322,24 +1322,69 @@
 ageRequest;%0A
+import org.springframework.data.domain.Sort;%0A
 import org.s
@@ -1727,36 +1727,135 @@
 til.
-stream.Collectors.groupingBy
+Comparator.reverseOrder;%0Aimport static java.util.stream.Collectors.groupingBy;%0Aimport static java.util.stream.Collectors.toList
 ;%0A%0A/
@@ -4364,16 +4364,17 @@
 model) %7B
+%09
 %0A%09model.
@@ -4387,32 +4387,35 @@
 ribute(%22posts%22, 
+%0A%09%09
 this.postReposit
@@ -4409,32 +4409,36 @@
 s.postRepository
+%0A%09%09%09
 .findAll().strea
@@ -4430,16 +4430,55 @@
 findAll(
+new Sort(Direction.DESC, %22publishedOn%22)
 ).stream
@@ -4479,16 +4479,20 @@
 stream()
+%0A%09%09%09
 .map(Pos
@@ -4498,16 +4498,20 @@
 st::new)
+%0A%09%09%09
 .collect
@@ -4511,27 +4511,16 @@
 collect(
-Collectors.
 grouping
@@ -4522,16 +4522,25 @@
 upingBy(
+%0A%09%09%09%09    
 post -%3E 
@@ -4578,18 +4578,115 @@
 Month(1)
-))
+, %0A%09%09%09%09    () -%3E new TreeMap%3CLocalDate, List%3CPost%3E%3E(reverseOrder()), %0A%09%09%09%09    toList()%0A%09%09%09%09)%0A%09%09%09)%0A%09
 );%0A%09retu

Use a tree map to sort archive