Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import in.shop2020.datalogger.EventType;
import in.shop2020.serving.utils.FileUtils;
import in.shop2020.serving.utils.Utils;
import in.shop2020.utils.DataLogger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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 com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @author rajveer
 * 
 */

@Results({
    @Result(name = "show", location = "compare-show.vm"),
    @Result(name = "redirect", location = "${redirectUrl}", type = "redirect", params={"statusCode", "301"})
})
public class CompareController extends BaseController {

    private static final long serialVersionUID = 1L;

    private static Logger logger = Logger.getLogger(Class.class);
    
    List<String> slides = new ArrayList<String>();
    
    private List<String> productList;
    private List<String> productNames;
    private List<String> productTitles;
    private Map<String, String> snippets;
    private List<String> unComparedSlides;
    private List<String> commonSlides;
    private Map<String, String> hyphenatedNames = new HashMap<String, String>();
    private String redirectUrl;
    private boolean comparable = false;
    
    private Map<String, String> slideNameImportanceMap;
    
    private Map<String, Map<String, Double>> productSlideScores;
    
    private List<String> importances = new ArrayList<String>();
    
    public CompareController() {
        super();
        importances.add("V. Imp");
        importances.add("Imp");
        importances.add("Not Imp");
    }

    @Actions({
        @Action("/compare-mobile-phones"),
        @Action("/compare-laptops"),
        @Action("/compare-tablets"),
        @Action("/compare-compact-cameras"),
        @Action("/compare-dslr-cameras"),
        @Action("/compare-battery"),
        @Action("/compare-bluetooth-headset"),
        @Action("/compare-external-dard-disks"),
        @Action("/compare-pen-drive"),
        @Action("/compare-memory-card"),
        @Action("/compare-face-plate"),
        @Action("/compare-car-charger"),
        @Action("/compare-decal"),
        @Action("/compare-headset"),
        @Action("/compare-data-cable"),
        @Action("/compare-carrying-case"),
        @Action("/compare-headphones"),
        @Action("/compare-speaker"),
        @Action("/compare-charger"),
        @Action("/compare-sceen-guard")
        
    })
    
    public String index() throws SecurityException, IOException {
        productList = new ArrayList<String>();
        StringBuffer prodNames = new StringBuffer("");
        StringBuffer requestParams = new StringBuffer("");
        if(request.getParameter("p1") != null){
            this.productList.add(request.getParameter("p1"));
        }
        if(request.getParameter("p2") != null){
            this.productList.add(request.getParameter("p2"));
        }
        if(request.getParameter("p3") != null){
            this.productList.add(request.getParameter("p3"));
        }
        if(request.getParameter("p4") != null){
            this.productList.add(request.getParameter("p4"));
        }
        if(request.getParameter("p5") != null){
            this.productList.add(request.getParameter("p5"));
        }
        boolean first = true;
        int i=1;
        for(String product : productList){              
                String hyphenatedName = getHyphenatedName(product);
                if(!hyphenatedName.equals("")){
                        if(first){
                                prodNames.append(hyphenatedName);
                                requestParams.append("?p"+ (i++) + "=" + product);
                                first = false;
                        } else {
                                prodNames.append("-vs-" + hyphenatedName);
                                requestParams.append("&p"+ (i++) + "=" + product);
                        }
                }
        }
        if(request.getParameter("fromsrc") != null){
                if(first){
                                requestParams.append("?fromsrc=" + request.getParameter("fromsrc"));
                                first = false;
                        } else {
                                requestParams.append("&fromsrc=" + request.getParameter("fromsrc"));
                        }
        }
        redirectUrl = "/" + ActionContext.getContext().getName() + "/" + prodNames.append(requestParams).toString().toLowerCase();
        logger.info("301 Redirection to " + redirectUrl);
        return "redirect";
    }
    
    public String show() throws SecurityException, IOException {
         logger.info(ActionContext.getContext().getName());
         productList = new ArrayList<String>();
         String fromsrc = "";
         if(request.getParameter("p1") != null){
             this.productList.add(request.getParameter("p1"));
         }
         if(request.getParameter("p2") != null){
             this.productList.add(request.getParameter("p2"));
         }
         if(request.getParameter("p3") != null){
             this.productList.add(request.getParameter("p3"));
         }
         if(request.getParameter("p4") != null){
             this.productList.add(request.getParameter("p4"));
         }
         if(request.getParameter("p5") != null){
             this.productList.add(request.getParameter("p5"));
         }
         if(request.getParameter("fromsrc") != null){
                 fromsrc = request.getParameter("fromsrc");
         }
         if(fromsrc!=null) {
                 DataLogger.logData(EventType.PRODUCT_COMPARE, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                                 StringUtils.join(productList, ", "), fromsrc);
         }
         return "show";
    }
    
    public List<String> getSlideNames() {
        productNames = new ArrayList<String>();
        productTitles = new ArrayList<String>();
        slideNameImportanceMap = new LinkedHashMap<String, String>();
        productSlideScores = new LinkedHashMap<String, Map<String, Double>>();
        Iterator<String> productListIterator = productList.iterator();
        while(productListIterator.hasNext()) {
                String productId = productListIterator.next();
            File f = new File(Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "SlideNamesSnippet.html");
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(f);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                String line;
                boolean isProductName = true;
                boolean isProductTitle = true;
                Map<String, Double> slideScores = new LinkedHashMap<String, Double>();
                while((line = br.readLine()) != null){
                    if(isProductName){
                        productNames.add(line);
                        hyphenatedNames.put(productId, line.replaceAll(" +", "-").replaceAll("/", "-").replaceAll("-+", "-"));
                        productSlideScores.put(line, slideScores);
                        isProductName = false;
                        continue;
                    }
                    if(isProductTitle){
                        productTitles.add(line);
                        isProductTitle = false;
                        continue;
                    }
                    
                    String[] parts = line.split("!!!");
                    String slideName = parts[0];
                    String importance = parts[1];
                    double score = Double.parseDouble(parts[2]);
                    if(score > 0){
                        if(!slideNameImportanceMap.containsKey(slideName)){
                            if(!importance.equals("None")){
                                slideNameImportanceMap.put(slideName, importance);
                                comparable = true;
                            }
                        }
                        if(!slideScores.containsKey(slideName)){
                            slideScores.put(slideName, score);
                        }
                    }
                    if(!slides.contains(slideName)){
                        slides.add(slideName);
                    }
                    
                }
            } catch (IOException e) {
                productListIterator.remove();
                logger.error("Error while reading snippet", e);
            }
        }
        logger.info(productNames);
        
        unComparedSlides = new ArrayList<String>();
        for(String slideName: slides){
            if(!slideNameImportanceMap.containsKey(slideName)){
                unComparedSlides.add(slideName);
            }
        }
        return slides;
    }
    
    public List<String> getUncomparedSlides(){
        return this.unComparedSlides;
    }
    
    public List<String> getcommonSlides(){
        return this.commonSlides;
    }
    
    public String getRedirectUrl(){
        return this.redirectUrl;        
    }
    
    public List<Double> getOverallScores(){
        List<Double> overallScores = new ArrayList<Double>();
        for(String productId : productSlideScores.keySet()){
            Map<String, Double> slideScores = productSlideScores.get(productId);
            double commulativeWeightedScore = 0.0;
            double commulativeWeights = 0.0;
            
            for(String slideName: slideNameImportanceMap.keySet()){
                double score = 0.0;
                if(slideScores.get(slideName) != null){
                    score = slideScores.get(slideName);
                }
                String importance = slideNameImportanceMap.get(slideName);
                if(importance.equals("V. Imp")){
                    commulativeWeightedScore += score*55;
                    commulativeWeights += 55;
                }
                if(importance.equals("Imp")){
                    commulativeWeightedScore += score*30;
                    commulativeWeights += 30;
                }
                if(importance.equals("Not Imp")){
                    commulativeWeightedScore += score*15;
                    commulativeWeights += 15;
                }
            }
            double weightedScore = commulativeWeightedScore/commulativeWeights;
            
            DecimalFormat oneDForm = new DecimalFormat("#.#");
            weightedScore = Double.valueOf(oneDForm.format(weightedScore));
            
            overallScores.add(weightedScore);
        }
        
         
        return overallScores;
    }
    
    public Map<String, String> getSnippets(){
        if (productList != null) {
            snippets = new LinkedHashMap<String, String>();
            for (String productId : productList) {
                try {
                    snippets.put(productId, FileUtils.read(Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "ComparisonSnippet.html"));
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        this.commonSlides = new ArrayList<String>();
        
        return snippets;
    }

    public Map<String, String> getProductSummarySnippets(){
        if (productList != null) {
            snippets = new LinkedHashMap<String, String>();
            for (String productId : productList) {
                try {
                    snippets.put(productId, FileUtils.read(Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "CompareProductSummarySnippet.html"));
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        return snippets;
    }
    public Map<String, String> getProductSnippets(){
        if (productList != null) {
            snippets = new LinkedHashMap<String, String>();
            for (String productId : productList) {
                try {
                    snippets.put(productId, FileUtils.read(Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "CompareProductSnippet.html"));
                } catch (IOException e) {
                    logger.error(e);
                }
            }

        }
        return snippets;
    }
    
    public List<String> getProductList(){
        return this.productList;
    }
    
    public List<String> getProductNames(){
        return this.productNames;
    }

    public String getPageTitle(){
        StringBuffer sb1 = new StringBuffer("Compare ");
        StringBuffer sb2 = new StringBuffer("");
        for(String title : this.productTitles) {
                sb2.append(" vs " + title);
        }
        sb2.replace(0, 3, "");
        return sb1.append(sb2).toString();
    }

    public String getPageDescription(){
        StringBuffer sb1 = new StringBuffer("Compare ");
        StringBuffer sb2 = new StringBuffer("");
        for(String name : this.productNames) {
                sb2.append(" vs " + name);
        }
        sb2.replace(0, 3, "");
        return sb1.append(sb2).append(" | Price, Specifications and Reviews ").toString();
    }
    
    public String getKeywords(){
        StringBuffer sb1 = new StringBuffer("Compare, ");
        StringBuffer sb2 = new StringBuffer("");
        for(String name : this.productNames) {
                sb2.append(", " + name);
        }
        sb2.replace(0, 2, "");
        return sb1.append(sb2).append(", Price, Specifications and Reviews ").toString();
        
    }

    public Map<String, String> getSlideNameImportanceMap(){
        return this.slideNameImportanceMap;
    }
    
    public Map<String, Map<String, Double>> getProductSlideScores(){
        return this.productSlideScores;
    }
    
    public List<String> getImportances(){
        return this.importances;
    }
    
    private String getHyphenatedName(String productId) {
        File f = new File(Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "SlideNamesSnippet.html");
        FileInputStream fis = null;
        String hyphenatedName = "";
         try {
             fis = new FileInputStream(f);
             BufferedReader br = new BufferedReader(new InputStreamReader(fis));
             hyphenatedName = br.readLine().replaceAll(" +", "-").replaceAll("/", "-").replaceAll("-+", "-");
         } catch (IOException e) {
             logger.error("Error while reading snippet", e);
         }
         return hyphenatedName;
    }
    
    public String getUrlForGeneratedCompareWith(String productId){
        return "/generated/" + hyphenatedNames.get(productId).toLowerCase() + "?p1=" + productId;
    }
    
    public String getUrlForProductPage(String productId){
        String hyphenatedCategory = ActionContext.getContext().getName();
        hyphenatedCategory = hyphenatedCategory.split("-", 2)[1];
        return "/" + hyphenatedCategory+ "/" + hyphenatedNames.get(productId).toLowerCase() + "-" + productId;
    }
    
    public String getActionName(){
        return ActionContext.getContext().getName();
    }
    
    public boolean isComparable() {
        return this.comparable;
    }
}