package gov.va.vss.web.interceptor;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Locale;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import gov.va.shared.util.SecurityUtil;
import gov.va.vss.model.facility.Kiosk;
import gov.va.vss.model.lookup.TemplateType;
import gov.va.vss.model.volunteer.Volunteer;

@Component
public class CommonReferenceDataInterceptor extends AbstractReferenceDataInterceptor {
	private static final Logger log = LoggerFactory.getLogger(AbstractReferenceDataInterceptor.class);

	@Value("${maxQuietPrinterStatusCheckMinutes}")
	private int maxQuietPrinterStatusCheckMinutes;

	@Value("${session.kiosk.idleAfterSeconds}")
	private int sessionIdleAfterSeconds;

	@Override
	protected void addAdditionalReferenceData(HttpServletRequest request, HttpServletResponse response, Object handler,
			Map<String, Object> model) throws Exception {
		Cookie kioskIdCookie = WebUtils.getCookie(request, "vssKioskId");
		Long kioskId = kioskIdCookie == null ? null : new Long(kioskIdCookie.getValue());

		Volunteer volunteerUser = SecurityUtil.getCurrentUserAs(Volunteer.class);

		if (volunteerUser != null) {
			model.put("currentUser", volunteerUser);
		}

		HttpSession session = request.getSession();

		session.setAttribute("sessionIdleAfterSeconds", new Integer(sessionIdleAfterSeconds));

		ZoneId timeZone = null;

		if (kioskId != null) {
			Kiosk kiosk = kioskDAO.findByPrimaryKey(kioskId);
			if (kiosk != null) {
				timeZone = kiosk.getFacility().getTimeZone();
				model.put("kiosk", kiosk);
				model.put("kioskPrinterStatusHealthy", kiosk.isPrinterOnline(maxQuietPrinterStatusCheckMinutes));
			}
		}

		ZonedDateTime now = ZonedDateTime.now();
		if (timeZone != null)
			now = now.withZoneSameInstant(timeZone);
		model.put("currentTime", now);

		/* Velocity caches these vals per the engine setup - CPB */
		Locale locale = LocaleContextHolder.getLocale();
		model.put("locale", locale.getLanguage());
		model.put("systemNotification", StringUtils.trim(velocityService
				.mergeTemplateIntoString(TemplateType.SYSTEM_NOTIFICATION.getName() + "." + locale.getLanguage())));
	}

}
