package org.ofbiz.product.category;

import java.util.Locale;
import java.util.Map;

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

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.GenericValue;

public class CategoryLocalizer {
	
	private Map uiLabelMap;
	private HttpSession session;
	private HttpServletRequest request;
	
    public CategoryLocalizer(HttpServletRequest request){
        this.session = request.getSession();
        this.request = request;
    }
    
    public CategoryLocalizer(HttpSession session){
        this.session = session;
    }
    
	public final String getDescription(GenericValue category){
		String retval = category.getString("description");
		if (retval==null|| retval.equals(null)){
			retval = "NoDescription";
		}
		retval = (String)getUiLabelMap().get(retval);
		return retval;
	}
	
	public final String getDescription(GenericValue category, int limit){
		String s = getDescription(category);
		if (s.length()<limit){
			s = s.substring(0,limit-3) + "...";
		}
		return s;
	}
	
	/**
	 * 
	 * @param category
	 * @param uiLabelMap
	 * @deprecated
	 * @return
	 */
	public static final String getDescription(GenericValue category,Map uiLabelMap){
		String retval = category.getString("description");
		if (retval==null|| retval.equals(null)){
			retval = "NoDescription";
		}
		retval = (String)uiLabelMap.get(retval);
		return retval;
	}
	
	public static final String inject(HttpServletRequest request,
			HttpServletResponse response) {
		CategoryLocalizer localizer = new CategoryLocalizer(request);
		request.setAttribute("categoryLocalizer", localizer);
		return "success";
	}
	
    public static final String getDescription(GenericValue category, HttpSession session){
        return new CategoryLocalizer(session).getDescription(category);
    }
    
	private synchronized Map getUiLabelMap() {
		if (uiLabelMap == null) {
			Locale locale = null;
			try {
				locale = (Locale) session.getAttribute("locale");

				if (locale == null) {
					locale = (Locale) session.getAttribute("initialLocale");
				}
			} catch (java.lang.IllegalStateException e) {
                if (request!=null){
    				locale = request.getLocale();
    				Debug.logWarning(
    						"Session was not valid using default locale from request "
    								+ locale, "product");
                }
			}
			if (locale == null) {
				locale = Locale.getDefault();
				Debug.logWarning(
						"Session was not valid using default locale from server "
								+ locale, "product");
			}
			Map map = UtilProperties.getResourceBundleMap(
					"ExtendedCategoriesUiLabels", locale);
			uiLabelMap = map;
		}
		return uiLabelMap;
	}
}