package controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import common.bean.UserData;
import common.controller.BaseController;

@Controller
public class IndexController extends BaseController {

	public IndexController(){
		super();
	}
	

	@RequestMapping(value={"/","/home","/home.do"}, method=RequestMethod.GET)	
	public String showHome(HttpServletRequest request, HttpServletResponse response) {
		setRequest(request);
		UserData datiUtente = getUserData();
		if (datiUtente==null) {
			clearCookies(request.getCookies(), response);
		}
		return "index";
	}

	private void clearCookies(Cookie[] cookies, HttpServletResponse response) {
		if (cookies!=null)
			for(Cookie cookie: cookies) {
				cookie.setValue(null);
				cookie.setMaxAge(0);
				cookie.setPath(cookie.getPath());
				response.addCookie(cookie);
			}
	}

	
	public Cookie getCookie(String cookieName, Cookie[] cookies) {
		if (cookies == null)
			return null;
		for(Cookie cookie: cookies)
			if (cookie.getName().equals(cookieName))
				return cookie;
		
		return null;
	}
}

