Subversion Repositories SmartDukaan

Rev

Rev 6998 | Rev 8179 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.serving.controllers;

import in.shop2020.serving.cache.EhcacheWrapper.CacheKeys;
import in.shop2020.serving.cache.SnippetCacheWrapper;
import in.shop2020.serving.services.SolrSearchService;
import in.shop2020.serving.utils.Utils;
import in.shop2020.utils.CategoryManager;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;

/**
 * @author rajveer
 *
 */
@Results({
        @Result(name = "show", location = "category-show.vm"),
        @Result(name = "redirect", location = "${redirectUrl}", type = "redirect", params={"statusCode", "301"})
})
public class CategoryController extends BaseController {
        
        private static final long serialVersionUID = 8477108528765030321L;

        private static Logger log = Logger.getLogger(Class.class);

        private List<String> results;
        private Map<String, String> snippets;
        private Map<String, List<String[]>> facets;
        private Map<String, List<List<String>>> crumbs;
        private Map<String, Double> dynamicSearchMap;
        /**
         * 
         */
        private String id;
        
        private String categoryName;
        private String redirectUrl;
        
        private String sortOrder = "F_50030+desc";
        private String sortUrl = "?";

        public String getRedirectUrl() {
                return redirectUrl;
        }


        private String categoryTitle;
        private String facetSelection = "";
        
        private String query;
        
        private Double minPrice;
        private Double maxPrice;
        private long categoryId;
        
        private long windowSize = 20;
        private long page = 1;
        private long totalResults;
        private long beginIndex = 0;
        private String url;
        private String priceUrl = "?";

        private String contextName;


        /**
         * GET /abc/10004
         * @throws Exception 
         * 
         */
        @Actions({
                @Action("/all-mobile-phones"),
                @Action("/all-mobile-accessories"),
                @Action("/all-tablets"),
                @Action("/all-laptops"),
                @Action("/all-cameras"),
                @Action("/business-phones"),
                @Action("/high-end-multimedia-phones"),
                @Action("/low-end-multimedia-phones"),
                @Action("/basic-phones"),
                @Action("/dslr-cameras"),
                @Action("/compact-cameras"),
                
                @Action("/bluetooth-headset"),
                @Action("/memory-card"),
                @Action("/battery"),
                @Action("/headset"),
                @Action("/charger"),
                @Action("/pen-drive"),
                @Action("/carrying-case"),
                @Action("/car-charger"),
                @Action("/screen-guard"),
                
                @Action("/face-plate"),
                @Action("/decal"),
                @Action("/data-cable"),
                @Action("/ear-buds"),
                @Action("/cleaning-kit"),
                @Action("/speaker"),
                @Action("/hard-disk-drive"),
                @Action("/external-hard-disks"),
                @Action("/headphones"),
                @Action("/portable-music-players"),
                @Action("/data-cards"),
                @Action("/power-banks"),
                @Action("/category")
        })
         
    public HttpHeaders show() throws Exception {
                contextName = ActionContext.getContext().getName();
        log.info("id=" + id);
        categoryId = Long.parseLong(id);
        this.categoryName = CategoryManager.getCategoryManager().getCategoryLabel(categoryId);
        
        if (categoryId == Utils.MOBILE_PHONES_CATEGORY || categoryId == Utils.MOBILE_ACCESSORIES_CATEGORY || categoryId == Utils.TABLETS_CATEGORY ){
                this.categoryTitle = categoryName + " Price List India" + " | " + this.categoryName;
        }
        else {
                this.categoryTitle = this.categoryName.replace("Phones", "Mobile Phones");
        }
        String[] fqrys = this.request.getParameterValues("fq");
        
        url = "?";
                
        query = "*";
        
        int length = 1;
        
        if(fqrys!= null){
                length += fqrys.length;
        }
        
        String[] newfqrys = new String[length];
        if(CategoryManager.getCategoryManager().getCategory(Long.parseLong(id)).getParent_category_id() == Utils.ROOT_CATEGORY){
                newfqrys[0] = "F_50010:"+categoryName;
        }else{
                newfqrys[0] = "F_50011:"+categoryName;
        }
        
        String urlCrumb = url;
        
        this.crumbs = new HashMap<String, List<List<String>>>();

        if(query != null) {
                urlCrumb = url; 
            }else {
                
        }
        
        if(fqrys != null) {
                log.info("fqrys=" + Arrays.toString(fqrys));
                String filterUrl = "";
                for(int i=0; i<fqrys.length; i++){
                        newfqrys[i+1] = fqrys[i];
                        urlCrumb += "&fq=" + URLEncoder.encode(fqrys[i], "UTF-8");
                        priceUrl += "&fq=" + URLEncoder.encode(fqrys[i], "UTF-8");
                        sortUrl += "&fq=" + URLEncoder.encode(fqrys[i], "UTF-8");
                        String facetName = StringUtils.split(fqrys[i], ":")[0];
                        String facetValue = StringUtils.split(fqrys[i], ":")[1];
                        String facetLabel = Utils.FACET_LABEL_MAP.get(facetName);
                        filterUrl = "&fq=" + URLEncoder.encode(fqrys[i], "UTF-8"); 
                        List<String> acrumb = Arrays.asList(facetValue, filterUrl);
                        if(!crumbs.containsKey(facetLabel)) {
                                crumbs.put(facetLabel, new ArrayList<List<String>>());
                        }
                        
                        this.crumbs.get(facetLabel).add(acrumb);
                }
        }
                url = urlCrumb;
                if(this.request.getParameter("minPrice") != null){
                        this.minPrice = (new Double(this.request.getParameter("minPrice")));
                        url= url + "&minPrice=" + this.request.getParameter("minPrice");
                }
                if(this.request.getParameter("maxPrice") != null){
                        this.maxPrice = (new Double(this.request.getParameter("maxPrice")));
                        url= url + "&maxPrice=" + this.request.getParameter("maxPrice");
                }
                
                sortUrl = url;
                
        if(this.request.getParameter("page") != null){
                this.page = Long.parseLong(this.request.getParameter("page"));
                this.beginIndex = this.windowSize * (this.page-1);
        }

        if(request.getParameter("sort")!=null){
                url= url + "&sort=" + this.request.getParameter("sort");
                sortOrder = this.request.getParameter("sort");
        }
        
        SolrSearchService search = new SolrSearchService(query, newfqrys, (page-1)*windowSize, windowSize, minPrice, maxPrice, "F_50028+asc," + sortOrder, sourceId);
        this.results =  search.getResultMap(); 
        this.dynamicSearchMap =  search.getDynamicPriceMap();

        setFacet(Arrays.asList(newfqrys), search);

        
        Map<String, Double> priceMap = search.getPriceStatsMap();
        if(priceMap != null){
                if (this.minPrice == null){
                        this.minPrice = priceMap.get("min");
                }
                if(this.maxPrice == null) {
                        this.maxPrice = priceMap.get("max");
                }
        }else{
                this.minPrice = 0.0;
                this.maxPrice = 0.0;
        }
        this.totalResults = search.getTotalResults();
        return new DefaultHttpHeaders("show");
    }
    
    public void setId(String id) {
        StringTokenizer tokenizer = new StringTokenizer(id,"-");
        while(tokenizer.hasMoreTokens()){
                this.id = tokenizer.nextToken();
        }
    }
    
    public String getId() {
        return this.id;
    }
    
    public String getCategoryName() {
        return this.categoryName;
    }
        
    public String getPageMetaDesc() {
        return "Best price "
                + this.facetSelection.replaceAll("Phones", "")
                + this.categoryName
                        .replaceAll("Mobile Phones", "mobile phones")
                        .replaceAll("Phones", "mobile phones")
                + " in India. Experience n' buy online. FREE Next Day delivery. Original product - Full manufacturer warranty. Comprehensive reviews."; 
    }
    
    public String getPageMetaKeywords() {
        if(CategoryManager.getCategoryManager().getCategory(Long.parseLong(id)).getParent_category_id()== Utils.MOBILE_PHONES_CATEGORY){
                return this.categoryName + ", mobile phone";
        }
        if(CategoryManager.getCategoryManager().getCategory(Long.parseLong(id)).getParent_category_id()== Utils.MOBILE_ACCESSORIES_CATEGORY){
                return this.categoryName + ", phone accessories";
        }
        return "";
    }
    
    public String getCategoryTitle() {
        return this.categoryTitle;
    }   
        
        public String getQuery() {
        return this.query;
    }
    
    
    public List<String> getResults() {
        return this.results;
    }
    
    public Map<String, List<String[]>> getFacets() {
        return this.facets;
    }
    
    public long getTotalResults(){
        return totalResults;
    }
    
    public String getUrl(){
        return this.url;
    }

        public long getBeginIndex(){
                if(totalResults>0)
                        return beginIndex+1;
                return beginIndex;
        }

        public long getTotalPages() {
                return 1 + (totalResults-1)/windowSize;
        }

        public long getCurrentPage() {
                return this.page;
        }

    public Double getMinPrice() {
        return this.minPrice;
    }
    
    public Double getMaxPrice() {
        return this.maxPrice;
    }
    
    public String getContextName() {
        return contextName;
    }
    
    public String getPriceUrl() {
        return this.priceUrl;
    }
    
    public Map<String, List<List<String>>> getCrumbs() {
        return this.crumbs;
    }

    public Map<String, String> getSnippets(){
        if(results != null){
                snippets = new HashMap<String, String>();       
                for(String docId: results){
                    String snippet = (String) SnippetCacheWrapper.getSnippet(CacheKeys.CATEGORY_SNIPPET_CACHE_KEY, docId, sourceId);
                    if (snippet != null) {
                        snippets.put(docId, snippet);
                    }
                        }
        }
                return snippets;
    }
    
    @Override
        public String getHeaderSnippet() {
                String url = request.getQueryString();
                if (url == null)        {
                        url = "";
                } else  {
                        url = "?" + url;
                }
                url = request.getRequestURI() + url;
                
                return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , categoryId, true);
        }
    @Override
        public String getCartWidgetSnippet() {
                return pageLoader.getCartWidgetSnippet(userinfo.getTotalItems(), userinfo.getTotalAmount(),categoryId);
        }
    
    private void setFacet(List<String> fqs, SolrSearchService search) throws Exception{
        List<String> filtrableFacets = search.getFilterableFacets();
        this.facets = new LinkedHashMap<String, List<String[]>>();
        for (String filtrableFacet : filtrableFacets) {
                
                Map<String, Integer> facetDetailMap = search.getFacetDetails(filtrableFacet);
                if(facetDetailMap==null)
                        continue;
                List<String[]> values = new ArrayList<String[]>();
                for(Entry<String, Integer> facetEntry : facetDetailMap.entrySet()){
                        String selected = "";
                        if(fqs.contains(filtrableFacet + ":" + facetEntry.getKey())) {
                                selected = "checked=\"checked\"";
                        }
                    String facet = facetEntry.getKey();
                        String drilldownURL = "&fq=" +  
                                URLEncoder.encode(filtrableFacet + ":" + facet, "UTF-8"); 
                        String[] afacet = new String[] { facet, 
                              facetEntry.getValue().toString(), drilldownURL,  selected};
                        values.add(afacet);    
                }
                
                this.facets.put(Utils.FACET_LABEL_MAP.get(filtrableFacet), values);
        }
        }
    
    public List<String> getChildren(String categoryLabel) {
        return SearchController.getCategoriesChildren().get(categoryLabel);
    }
    
        public String getDynamicSearchMap(){
        if (this.dynamicSearchMap == null) {
                return "{}";
        } else {
                return new Gson().toJson(this.dynamicSearchMap);
        }
    }
        
        public String getSortOrder(){
                return this.sortOrder;
        }
        
        public String getSortUrl(){
                return this.sortUrl;
        }

}