/*******************************************************************************
 * Copyright 2Fi Business Solutions Ltd.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.tbms.root.web;

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

import com.ffii.core.Session;
import com.ffii.core.Settings;
import com.ffii.core.setting.service.SettingsService;
import com.ffii.core.utils.LocaleUtils;
import com.ffii.core.web.AbstractController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class IndexController extends AbstractController {

	@Autowired
	private SettingsService settingsService;

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) {

		// get available locales and default locale from system settings
		String[] availableLocales = settingsService.getString(Settings.SYS_AVAILABLE_LOCALES).split(",");
		Session.setAttribute(request, Session.AVAILABLE_LOCALES, availableLocales);

		String defaultLocale = settingsService.getString(Settings.SYS_DEFAULT_LOCALE);

		// try to resolve current locale
		String currentLocale = LocaleUtils.resolveLocaleString(request);

		// determine if current locale is available
		boolean localeIsAvailable = false;
		for (String availableLocale : availableLocales) {
			if (availableLocale.equalsIgnoreCase(currentLocale)) {
				localeIsAvailable = true;
			}
		}

		// use current locale if available, else use default locale
		if (localeIsAvailable) {
			LocaleUtils.setLocale(request, response, LocaleUtils.toLocale(currentLocale));
		} else {
			LocaleUtils.setLocale(request, response, LocaleUtils.toLocale(defaultLocale));
		}

		// find username cookie
		/*
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("username".equals(cookie.getName())) {
					model.addAttribute("username", cookie.getValue());
				}
			}
		}
		*/

		return "root/index";
	}
}