package org.iri_research.renkan.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.iri_research.renkan.Constants;
import org.iri_research.renkan.models.Project;
import org.iri_research.renkan.models.Space;
import org.iri_research.renkan.repositories.ProjectsRepository;
import org.iri_research.renkan.repositories.SpacesRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefaults;
import org.springframework.http.HttpStatus;
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.RequestMethod;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/")
public class RenkanRootController {

	private final Logger logger = LoggerFactory.getLogger(RenkanRootController.class);
		
	@Autowired
	private ProjectsRepository projectsRepository;
	
	@Autowired
	private SpacesRepository spacesRepository;
	
	private String buildBaseUrl(HttpServletRequest request) {
		StringBuffer baseUrl = request.getRequestURL();
		boolean firstParam = true;
		Enumeration<?> namesEnum = request.getParameterNames();
		while(namesEnum.hasMoreElements()) {
			String paramName = 
					(String)namesEnum.nextElement();
			
			if("p.page".equals(paramName)) {
				continue;
			}
			for(String val:request.getParameterValues(paramName)) {
				if(firstParam) {
					baseUrl.append('?');
					firstParam = false;		
				}
				else {
					baseUrl.append('&');
				}
				baseUrl.append(paramName).append('=').append(val);
			}			
		}
		return baseUrl.toString();
	}
		
	@RequestMapping(value="", method = RequestMethod.GET, produces={"text/html;charset=UTF-8"})
	public String renkanIndex(Model model, @PageableDefaults(sort={"created"}, sortDir=Direction.DESC, value=Constants.PAGINATION_SIZE) Pageable p, HttpServletRequest request) {

		Page<Space> page = this.spacesRepository.findAll(p);
		//Iterable<Space> spaces = this.spacesRepository.findAll();
		
				
		model.addAttribute("page", page);
		model.addAttribute("baseUrl", this.buildBaseUrl(request));
		model.addAttribute("projectsCount", this.projectsRepository.getCountBySpace());
		
		return "renkanIndex";
	}

	@RequestMapping(value="/s/{space_id}", method = RequestMethod.GET, produces={"text/html;charset=UTF-8"})
	public ModelAndView spaceIndex(@PathVariable("space_id") String spaceId, @PageableDefaults(sort={"created"}, sortDir=Direction.DESC, value=Constants.PAGINATION_SIZE) Pageable p, HttpServletRequest request) {
		
		logger.debug("SpaceId : " + (spaceId== null ? "null" : spaceId));
		
		Map<String, Object> model = new HashMap<String, Object>();

		if("_".equals(spaceId)) {
			spaceId = null;
		}
		
		Space space = this.spacesRepository.findOne(spaceId);
		
		if(null == space) {
			throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Space " + spaceId + " not found.");
		}
		
		model.put("space", space);
		
		Page<Project> page = this.projectsRepository.findBySpaceId(spaceId, p);
		
		model.put("page", page);
		model.put("baseUrl", this.buildBaseUrl(request));
		
		return new ModelAndView("projectIndex", model);
	}
	
		
}
