/*******************************************************************************
 * 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.core.security.web.authentication;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

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

import com.ffii.core.Session;
import com.ffii.core.Settings;
import com.ffii.core.security.service.LoginLogService;
import com.ffii.core.setting.service.SettingsService;
import com.ffii.core.utils.JsonUtils;
import com.ffii.core.utils.LocaleUtils;
import com.ffii.core.utils.Params;
import com.ffii.core.utils.SecurityUtils;
import com.ffii.core.utils.web.ServletResponseUtils;
import com.ffii.core.web.view.AbstractView;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils;

/**
 * <tt>AuthenticationSuccessHandler</tt> implementation which return a success JSON String upon successful authentication.
 *
 * @author Patrick
 */
public class JsonAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private RequestCache requestCache = new HttpSessionRequestCache();

	@Autowired
	private LoginLogService loginLogService;

	@Autowired
	private SettingsService settingsService;

	/**
	 * Returns the successful JSON String to client, unless the account is locked.
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		logger.info("Authentication Success: " + authentication.getName() + " [" + request.getRemoteAddr() + "]");

		ServletResponseUtils.disableCaching(response);
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.setCharacterEncoding("UTF-8");

		// save available locales to session
		String[] availableLocales = settingsService.getString(Settings.SYS_AVAILABLE_LOCALES).split(",");
		Session.setAttribute(request, Session.AVAILABLE_LOCALES, availableLocales);

		// set user's default locale
		String locale = SecurityUtils.getUser().getLocale();
		if (!StringUtils.isEmpty(locale))
			WebUtils.setSessionAttribute(request, SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, LocaleUtils.toLocale(locale));

		// extra values to be passed to client
		Map<String, Object> values = new HashMap<String, Object>();

		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (savedRequest != null) {
			String targetUrlParameter = getTargetUrlParameter();
			if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
				requestCache.removeRequest(request, response);
				authenticationSuccess(request, response, null);
				return;
			}

			// Use the DefaultSavedRequest URL
			String targetUrl = savedRequest.getRedirectUrl();
			logger.debug("Sending DefaultSavedRequest Url: " + targetUrl);

			// target URL to redirect to (if any)
			values.put("targetUrl", URLEncoder.encode(targetUrl, "UTF-8"));
		}

		authenticationSuccess(request, response, values);
	}

	protected void authenticationSuccess(HttpServletRequest request, HttpServletResponse response, Map<String, Object> values)
			throws UnsupportedEncodingException, IOException {

		Map<String, Object> args = new HashMap<String, Object>();
		args.put(Params.SUCCESS, Boolean.TRUE);
		if (values != null) args.putAll(values);

		clearAuthenticationAttributes(request);
		ServletResponseUtils.writeStringToStream(response, AbstractView.CHARSET_UTF8, JsonUtils.toJsonString(args));

		// log successful login
		loginLogService.createLoginLog(SecurityUtils.getUser().getUsername(), request.getRemoteAddr(), true);

	}

}
