package com.agilex.vamf.utils;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.agilex.healthcare.mobilehealthplatform.domain.filter.datefilter.DateFilter;
import com.agilex.healthcare.utility.DateHelper;
import com.agilex.healthcare.utility.NullChecker;

public class SessionStateHelper {
	private static final Logger LOGGER = Logger.getLogger(SessionStateHelper.class);
	private boolean cacheEnabled = false;
	
	public SessionStateHelper(boolean cacheEnabled) {
		this.cacheEnabled = cacheEnabled;
	}

	public boolean isCacheEnabled() {
		return this.cacheEnabled;
	}
	
	public Object checkCache(HttpSession session, String cacheKey) {
		return checkCache(session, cacheKey, null);
	}
	
	public Object checkCache(HttpSession session, String cacheKey, int attempts) {
		return checkCache(session, cacheKey, null, attempts);
	}
	
	public Object checkCache(HttpSession session, String cacheKey, DateFilter dateFilter) {
		return checkCache(session, cacheKey, dateFilter, 1);
	}
	
	public Object checkCache(HttpSession session, String cacheKey, DateFilter dateFilter, int attempts) {
		Object cachedObject = null;
		
		if (cacheEnabled) {
			while (attempts > 0 && cachedObject == null) {
				@SuppressWarnings("unchecked")
				HashMap<String, Object> cacheMap = (HashMap<String, Object>) session.getAttribute(cacheKey);
				
				if (cacheMap != null) {
					cachedObject = cacheMap.get(createDateRangeKey(dateFilter));
					if (cachedObject != null) {
						break;
					}
				}
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					LOGGER.warn("Error sleeping checkCache thread", e);
				}
				
				attempts--;
			}
		}
		
		return cachedObject;
	}

	public String createDateRangeKey(DateFilter dateFilter) {
		String result = "";
		if (dateFilter != null) {
			String startDate = createDateString(dateFilter.getStartDate()); 
			String endDate = createDateString(dateFilter.getEndDate());
			result = startDate + endDate;
		}
		return result;
	}
	
	private String createDateString(Date date) {
		return NullChecker.isNullish(date) ? "-" :DateHelper.formatDate(date);
	}
	
	public void addCacheMapToSession(HttpSession session, String cacheKey, Object object) {
		addCacheMapToSession(session, cacheKey, null, object);
	}
	
	public void addCacheMapToSession(HttpSession session, String cacheKey, DateFilter dateFilter, Object object) {
		if (cacheEnabled) {
			if (object == null) {
				return;
			}
			
			HashMap<String, Object> cacheMap = new HashMap<String, Object>();
			cacheMap.put(createDateRangeKey(dateFilter), object);
			session.setAttribute(cacheKey, cacheMap);
		}
	}
}

