Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.catalog.dashboard.server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import in.shop2020.catalog.dashboard.client.CatalogService;
import in.shop2020.catalog.dashboard.shared.BulkItemPricing;
import in.shop2020.catalog.dashboard.shared.CategoryHsnCode;
import in.shop2020.catalog.dashboard.shared.Item;
import in.shop2020.catalog.dashboard.shared.ItemInventory;
import in.shop2020.catalog.dashboard.shared.ItemStatus;
import in.shop2020.catalog.dashboard.shared.ItemWarehouse;
import in.shop2020.catalog.dashboard.shared.ItemsComparator;
import in.shop2020.catalog.dashboard.shared.SourcePricings;
import in.shop2020.catalog.dashboard.shared.VendorItemMapping;
import in.shop2020.catalog.dashboard.shared.VendorPricings;
import in.shop2020.catalog.dashboard.shared.VoucherItemMapping;
import in.shop2020.config.ConfigException;
import in.shop2020.content.ContentService;
import in.shop2020.content.ContentServiceException;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.Insurer;
import in.shop2020.model.v1.catalog.ItemType;
import in.shop2020.model.v1.catalog.PrivateDeal;
import in.shop2020.model.v1.catalog.status;
import in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems;
import in.shop2020.model.v1.inventory.InventoryService;
import in.shop2020.model.v1.inventory.ItemStockPurchaseParams;
import in.shop2020.model.v1.inventory.OOSStatus;
import in.shop2020.model.v1.inventory.StateInfo;
import in.shop2020.model.v1.inventory.VatType;
import in.shop2020.model.v1.user.VoucherType;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.ContentClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.config.ConfigClient;
import in.shop2020.utils.CategoryManager;
import in.shop2020.utils.ConfigClientKeys;

@SuppressWarnings("serial")
public class CatalogServiceImpl extends RemoteServiceServlet implements CatalogService {

        private static Logger logger = Logger.getLogger(CatalogServiceImpl.class);

        private static Logger pushToProdLogger = Logger.getLogger("pushToProdLogger");

        private static Date pushToProdDate;

        private static String logFile;

        private static int maxCount;

        private static final int EBAYSOURCE = 6;
        private static final int SNAPDEALSOURCE = 7;
        private static final int FLIPKARTSOURCE = 8;
        private static final int HOMESHOP18SOURCE = 4;
        
        private static final long DEFAULTQUANTIYSTEP = 1;
        private static final long DEFAULTMINBUYQTY =1;
        private static final long DEFAULTMAXBUYQTY = 0;

        List<Item> privateDealitemList;

        static {
                try {
                        logFile = ConfigClient.getClient().get(ConfigClientKeys.push_prices_to_prod_log_file.toString());
                        maxCount = Integer.parseInt(ConfigClient.getClient().get(ConfigClientKeys.push_prices_to_prod_max_count.toString()));    
                } catch(ConfigException ce) {
                        logger.error("Unable to connect to the config server. Setting sensible defaults.", ce);
                        logFile = "/var/log/services/pushToProductionCount/pushToProd.log";
                        maxCount = 5;
                }

        }

        @Override
        public int getItemCountByStatus(boolean useStatus, ItemStatus itemStatus){
                int count = 0;
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        status stat = status.findByValue(itemStatus.getValue());
                        count = catalogClient.getItemCountByStatus(useStatus, stat);
                }catch(Exception e){
                        logger.error("Error while getting the count of items from the catalog service", e);
                }
                return count;
        }

        @Override
        public List<Item> getInventoryOutofSyncItems(int offset, int limit){
                List<Item> itemList = new ArrayList<Item>();

                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getAllIgnoredInventoryUpdateItemsList(offset, limit);

                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all items from the catalog service", e);
                }
                return itemList;
        }

        @Override
        public int getInventoryOutofSyncItemsCount(){
                int count=0;
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                        count = inventoryClient.getAllIgnoredInventoryupdateItemsCount();

                } catch (Exception e) {
                        logger.error("Error while getting all items from the catalog service", e);
                }
                return count;   
        }

        public List<Item> getPrivateDealItems(int offset,int limit){
                privateDealitemList = new ArrayList<Item>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getPrivateDealItems(offset, limit);

                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                privateDealitemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all items from the catalog service", e);
                }
                return privateDealitemList;
        }
        public int getPrivateDealItemsCount(){
                if(privateDealitemList!=null)
                        return privateDealitemList.size();
                else
                        return 0;
        }

        @Override
        public List<Item> getAllItems(int start, int limit) {
                List<Item> itemList = new ArrayList<Item>();
                logger.error("Inside get All Items");
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getAllItemsInRange(start, limit);
                        logger.error("Before get item from thrift");
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                        logger.error("After get item from thrift");
                } catch (Exception e) {
                        logger.error("Error while getting all items from the catalog service", e);
                }
                logger.error("Item List return Size "+ itemList.size());
                return itemList;
        }

        public List<Item> getAllActiveItems(int start, int limit){
                return getItemsByStatus(status.ACTIVE, start, limit);
        }

        @Override
        public List<Item> getAllPhasedOutItems(int start, int limit){
                return getItemsByStatus(status.PHASED_OUT, start, limit);
        }

        @Override
        public List<Item> getAllPausedItems(int start, int limit){
                return getItemsByStatus(status.PAUSED, start, limit);
        }

        @Override
        public List<Item> getAllInProcessItems(int start, int limit) {
                return getItemsByStatus(status.IN_PROCESS, start, limit);
        }

        @Override
        public List<Item> getAllContentCompleteItems(int start, int limit) {
                return getItemsByStatus(status.CONTENT_COMPLETE, start, limit);
        }

        public List<Item> getBestDeals(){
                List<Item> itemList = new ArrayList<Item>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getBestDeals();
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch(Exception e){
                        logger.error("Error while getting the best deals from the catalog service", e);
                }
                //Collections.sort(itemList, new ItemsComparator());
                return itemList;
        }

        @Override
        public List<Item> getRiskyItems() {
                List<Item> itemList = new ArrayList<Item>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getItemsByRiskyFlag();
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch(Exception e){
                        logger.error("Error while getting the risky items from the catalog service", e);
                }
                Collections.sort(itemList, new ItemsComparator());
                return itemList;
        }

        public List<Item> getBestSellers(){
                List<Item> itemList = new ArrayList<Item>();

                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getBestSellers();
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch(Exception e){
                        logger.error("Error while getting the best sellers from the catalog service", e);
                }
                return itemList;        
        }

        @Override
        public boolean addtoIgnoredInventoryUpdateItemsIdsWarehouseIds(long itemId,long warehouseId){
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        return inventoryClient.insertItemtoIgnoreInventoryUpdatelist(itemId, warehouseId);
                } catch (Exception e) {
                        logger.error("Error while inserting item to ignore inventory update list", e);
                }
                return false;
        }

        @Override
        public boolean deleteFromIgnoredInventoryUpdateItemsIdsWarehouseIds(long itemId,long warehouseId){
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        return inventoryClient.deleteItemFromIgnoredInventoryUpdateList(itemId,warehouseId);

                } catch (Exception e) {
                        logger.error("Error while inserting item to ignore inventory update list", e);
                }
                return false;
        }



        @Override
        public List<Item> getLatestArrivals(){
                List<Item> itemList = new ArrayList<Item>();

                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getLatestArrivals();
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                //List<in.shop2020.model.v1.inventory.VendorItemPricing> vip = catalogClient.getAllItemPricing(thriftItem.getId());
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null));
                        }
                } catch(Exception e){
                        logger.error("Error while getting the latest arrivals from the catalog service", e);
                }
                return itemList;
        }

        @Override
        public List<Item> searchItems(int start, int limit, List<String> searchTerms) {
                List<Item> itemList = new ArrayList<Item>();

                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.searchItemsInRange(searchTerms, start, limit);
                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null,null));
                        }
                } catch(Exception e){
                        logger.error("Error while getting the search results from the catalog service", e);
                }
                return itemList;
        }

        @Override
        public int getSearchResultCount(List<String> searchTerms){
                int count = 0;
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        count = catalogClient.getSearchResultCount(searchTerms);
                } catch(Exception e){
                        logger.error("Error while getting the search results from the catalog service", e);
                }

                return count;
        }

        public Item getItem(long itemId){
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        in.shop2020.model.v1.catalog.Item thriftItem = catalogClient.getItem(itemId);
                        PrivateDeal privateDeal = catalogClient.getPrivateDealDetails(itemId);
                        Long catalogItemId = thriftItem.getCatalogItemId();
                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getItemsByCatalogId(catalogItemId);
                        List <Long> sameItemsWithDifferentColors = new ArrayList<Long>();
                        if(thriftItems.size()>1){
                                for(in.shop2020.model.v1.catalog.Item tItem : thriftItems ){
                                        Long id = tItem.getId();
                                        if(!id.equals(itemId)){
                                                sameItemsWithDifferentColors.add(id); 
                                        }
                                }
                        }
                        List<in.shop2020.model.v1.inventory.VendorItemPricing> vip = inventoryClient.getAllItemPricing(thriftItem.getId());
                        Map<Long,StateInfo> stateIdNameMap = inventoryClient.getStateMaster();

                        List<in.shop2020.model.v1.inventory.VendorItemMapping> vim = inventoryClient.getVendorItemMappings(thriftItem.getId());
                        List<in.shop2020.model.v1.catalog.SourceItemPricing> sip = catalogClient.getAllSourcePricing(thriftItem.getId());
                        List<in.shop2020.model.v1.catalog.Item> sit = catalogClient.getAllSimilarItems(thriftItem.getId());
                        in.shop2020.model.v1.inventory.ItemInventory itemInventory = inventoryClient.getItemInventoryByItemId(thriftItem.getId());
                        ItemStockPurchaseParams stockPurchaseParams = inventoryClient.getItemStockPurchaseParams(thriftItem.getId());
                        Map<Long, String> saleHistory = new HashMap<Long, String>();
                        List<OOSStatus> oosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 0, 5);
                        String lastNdaySale = getOosString(oosStatuses);
                        saleHistory.put(0L,lastNdaySale);
                        List<OOSStatus> webOosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 1, 5);
                        String webLastNdaySale = getOosString(webOosStatuses);
                        saleHistory.put(1L,webLastNdaySale);
                        List<OOSStatus> amzOosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 3, 5);
                        String amzLastNdaySale = getOosString(amzOosStatuses);
                        saleHistory.put(3L,amzLastNdaySale);
                        List<OOSStatus> ebayOosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 6, 5);
                        String ebayLastNdaySale = getOosString(ebayOosStatuses);
                        saleHistory.put(6L,ebayLastNdaySale);
                        List<OOSStatus> spdOosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 7, 5);
                        String spdLastNdaySale = getOosString(spdOosStatuses);
                        saleHistory.put(7L,spdLastNdaySale);
                        List<OOSStatus> fktOosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 8, 5);
                        String fktLastNdaySale = getOosString(fktOosStatuses);
                        saleHistory.put(8L,fktLastNdaySale);
                        List<OOSStatus> hs18OosStatuses = inventoryClient.getOosStatusesForXDaysForItem(thriftItem.getId(), 4, 5);
                        String hs18LastNdaySale = getOosString(hs18OosStatuses);
                        saleHistory.put(4L,hs18LastNdaySale);
                        Long freebieItemId = catalogClient.getFreebieForItem(thriftItem.getId());
                        List<in.shop2020.model.v1.catalog.VoucherItemMapping> tvouchers = catalogClient.getAllItemVouchers(thriftItem.getId());
                        Map<String,String> stateNameVatPercentageMap = new HashMap<String,String>();
                        catalogClient =  new CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").getClient();
                        double vatrate;
                        for(Entry<Long, StateInfo> entry:stateIdNameMap.entrySet()){
                                vatrate = -1.0;
                                StateInfo state = entry.getValue();
                                double price = state.getVatType().equals(VatType.MRP)? thriftItem.getMrp() : thriftItem.getSellingPrice();
                                if(price > 0){
                                        try{
                                                vatrate = catalogClient.getVatPercentageForItem(thriftItem.getId(),entry.getKey(),price);
                                        }
                                        catch(CatalogServiceException cex){
                                                vatrate = -1.0;
                                        }
                                } else {
                                        vatrate = -2.0;
                                }
                                if(vatrate != -2.0) {
                                        stateNameVatPercentageMap.put(state.getStateName(),String.valueOf(vatrate));
                                } else {
                                        stateNameVatPercentageMap.put(state.getStateName(),"MRP needed");
                                }
                        }
                        Item it = getItemFromThriftItem(thriftItem, vip, vim, sip, sit, itemInventory, tvouchers, stockPurchaseParams, saleHistory, freebieItemId , stateNameVatPercentageMap,privateDeal);
                        it.setSameItemsWithDifferentColors(sameItemsWithDifferentColors);
                        return it;
                }catch(Exception e){
                        logger.error("Error while getting the item from the catalog service", e);
                }
                return null;
        }

        private String getOosString(List<OOSStatus> oosStatuses){
                String lastNdaySale = "";
                for(OOSStatus oosStatus : oosStatuses){
                        if(oosStatus.isIs_oos()){
                                lastNdaySale += "X-";
                        }else{
                                lastNdaySale += oosStatus.getNum_orders() + "-";
                        }
                }
                if(lastNdaySale!=""){
                        lastNdaySale = lastNdaySale.substring(0, lastNdaySale.length()-1);
                }
                return lastNdaySale;
        }

        @Override
        public boolean updateItem(Item item) {
                logger.info("Updating item with Id: " + item.getId());
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        in.shop2020.model.v1.catalog.Item tItem = catalogClient.getItem(item.getId());
                        in.shop2020.model.v1.catalog.PrivateDeal privateDeal = new in.shop2020.model.v1.catalog.PrivateDeal(); 
                        privateDeal.setItem_id(item.getId());
                        privateDeal.setDealFreebieItemId(item.getPrivateDeal().getDealFreebieItemId());
                        privateDeal.setDealPrice(item.getPrivateDeal().getDealPrice());
                        privateDeal.setDealText(item.getPrivateDeal().getDealText());
                        privateDeal.setDealFreebieOption(item.getPrivateDeal().getDealFreebieOption());
                        privateDeal.setDealTextOption(item.getPrivateDeal().getDealTextOption());
                        if(item.getPrivateDeal().getEndDate()!=null){
                                privateDeal.setEndDate(item.getPrivateDeal().getEndDate());
                        }
                        if(item.getPrivateDeal().getStartDate()!=null){
                                privateDeal.setStartDate(item.getPrivateDeal().getStartDate());
                        }
                        privateDeal.setIsCod(item.getPrivateDeal().isCod());
                        privateDeal.setRank(item.getPrivateDeal().getRank());
                        privateDeal.setIsActive(item.getPrivateDeal().isActive());
                        if(privateDeal.getDealPrice() > 0 && privateDeal.getEndDate()!=0 && privateDeal.getStartDate()!=0){
                                logger.info("Updating Private deal: " + item.getId());
                                logger.info("Deal Price "+privateDeal.getDealPrice());
                                logger.info("Deal Start Date "+privateDeal.getStartDate());
                                logger.info("Deal End Date "+privateDeal.getEndDate());
                                logger.info("Has COD on deal: " + privateDeal.isIsCod());
                                logger.info("Response" + catalogClient.addOrUpdatePrivateDeal(privateDeal));
                                logger.info("Updated Private deal: " + item.getId());
                        }
                        else{
                                logger.info("Skipping Private deal: " + item.getId());
                                logger.info("Deal Price "+privateDeal.getDealPrice());
                                logger.info("Deal Start Date "+privateDeal.getStartDate());
                                logger.info("Deal End Date "+privateDeal.getEndDate());
                        }
                        setThriftItemParams(tItem, item);
                        long rItemId;
                        if((rItemId = catalogClient.updateItem(tItem)) != item.getId()) {
                                logger.error("Error updating item, returned Item Id: " + rItemId);
                                return false;
                        }
                        logger.info("Successfully updated item with id: " + item.getId());
                        
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        
                        Map<String, VendorItemMapping> vendorMappings = item.getVendorKeysMap();
                        if(vendorMappings != null && !vendorMappings.isEmpty()) {
                                in.shop2020.model.v1.inventory.VendorItemMapping tVendorMapping;

                                for(Entry<String, VendorItemMapping> e : vendorMappings.entrySet()) {
                                        tVendorMapping = new in.shop2020.model.v1.inventory.VendorItemMapping();
                                        VendorItemMapping v = e.getValue();
                                        tVendorMapping.setVendorId(v.getVendorId());
                                        tVendorMapping.setItemKey(v.getItemKey());
                                        tVendorMapping.setItemId(item.getId());
                                        inventoryClient.addVendorItemMapping(e.getKey().substring(e.getKey().indexOf(Item.KEY_SEPARATOR)+1), tVendorMapping);
                                        logger.info("Updates VendorItemMapping: " + tVendorMapping.toString());
                                }
                        }

                        if(item.getMinStockLevel()!=0 || item.getNumOfDaysStock()!=0) {
                                inventoryClient.updateItemStockPurchaseParams(item.getId(), item.getNumOfDaysStock(),
                                                item.getMinStockLevel());
                        }

                        if(item.getFreebieItemId()!=null) {
                                in.shop2020.model.v1.catalog.FreebieItem freebieItem = new in.shop2020.model.v1.catalog.FreebieItem();
                                freebieItem.setItemId(item.getId());
                                freebieItem.setFreebieItemId(item.getFreebieItemId());
                                catalogClient.addOrUpdateFreebieForItem(freebieItem);
                        }

                        Map<Long, VendorPricings> vendorPricings = item.getVendorPricesMap();
                        if(vendorPricings != null && !vendorPricings.isEmpty()) {
                                in.shop2020.model.v1.inventory.VendorItemPricing tVendorPricing;
                                for(VendorPricings v : vendorPricings.values()) {
                                        tVendorPricing = new in.shop2020.model.v1.inventory.VendorItemPricing();
                                        tVendorPricing.setVendorId(v.getVendorId());
                                        tVendorPricing.setItemId(item.getId());
                                        tVendorPricing.setMop(v.getMop());
                                        tVendorPricing.setTransferPrice(v.getTransferPrice());
                                        tVendorPricing.setDealerPrice(v.getDealerPrice());
                                        tVendorPricing.setNlc(v.getNlc());
                                        inventoryClient.addVendorItemPricing(tVendorPricing);
                                        logger.info("Updated VendorItemPricing: " + tVendorPricing.toString());
                                }
                        }

                        Map<Long, SourcePricings> sourcePricings = item.getSourcePricesMap();
                        if(sourcePricings != null && !sourcePricings.isEmpty()) {
                                in.shop2020.model.v1.catalog.SourceItemPricing tSourcePricings;
                                for(SourcePricings s : sourcePricings.values()) {
                                        tSourcePricings = new in.shop2020.model.v1.catalog.SourceItemPricing();
                                        tSourcePricings.setSourceId(s.getSourceId());
                                        tSourcePricings.setItemId(item.getId());
                                        tSourcePricings.setMrp(s.getMrp());
                                        tSourcePricings.setSellingPrice(s.getSellingPrice());
                                        catalogClient.addSourceItemPricing(tSourcePricings);
                                        logger.info("Updated SourceItemPricing: " + tSourcePricings.toString());
                                }
                        }

                }catch(Exception e){
                        logger.error("Error while updating item: ", e);
                        return false;
                }
                return true;
        }

        @Override
        public List<Long> getMonitoredWarehouseIdsForVendors(List<Long> vendorIds){
                List<Long> monitoredWarehouseids=null;
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        monitoredWarehouseids = inventoryClient.getMonitoredWarehouseForVendors(vendorIds);
                } catch (Exception e) {
                        logger.error("Error while getting Monitored warehouse for vendor: ", e);
                }
                return monitoredWarehouseids;

        }

        @Override
        public List<ItemWarehouse> getignoredInventoryUpdateItemsIdsWarehouseIds(){
                List<ItemWarehouse> ignoredItemIdwarehouseIdList = new ArrayList<ItemWarehouse>();
                try {

                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        List<IgnoredInventoryUpdateItems> ignoredInventoryUpdateItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
                        for(IgnoredInventoryUpdateItems ignoredInventoryUpdateItem:ignoredInventoryUpdateItems){
                                ignoredItemIdwarehouseIdList.add(new ItemWarehouse(ignoredInventoryUpdateItem.getItemId(),ignoredInventoryUpdateItem.getWarehouseId()));
                        }


                } catch (Exception e) {
                        logger.error("Error while getting Monitored warehouseid and itemid : ", e);
                }
                return ignoredItemIdwarehouseIdList;

        }
        @Override
        public Map<Long, String> getAllVendors() {
                Map<Long, String> vendorMap = new HashMap<Long, String>();
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                        List<in.shop2020.model.v1.inventory.Vendor> vendors = inventoryClient.getAllVendors();

                        for(in.shop2020.model.v1.inventory.Vendor v : vendors) {
                                vendorMap.put(v.getId(), v.getName());
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the vendors: ", e);
                }
                return vendorMap;
        }

        @Override
        public Map<Long, String> getAllSources() {
                Map<Long, String> sourceMap = new HashMap<Long, String>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Source> sources = catalogClient.getAllSources();

                        for(in.shop2020.model.v1.catalog.Source s : sources) {
                                sourceMap.put(s.getId(), s.getName());
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the vendors: ", e);
                }
                return sourceMap;
        }

        @Override
        public Map<Long, String> getShippingWarehouses() {
                Map<Long, String> warehouseMap = new HashMap<Long, String>();
                Set<Long> shippingLocations = new HashSet<Long>();
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                        List<in.shop2020.model.v1.inventory.Warehouse> warehouses = inventoryClient.getAllWarehouses(true);

                        for(in.shop2020.model.v1.inventory.Warehouse warehouse : warehouses) {
                                shippingLocations.add(warehouse.getShippingWarehouseId());
                        }

                        for(in.shop2020.model.v1.inventory.Warehouse warehouse : warehouses) {
                                if (shippingLocations.contains(warehouse.getId())) {
                                        warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
                                }                
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the warehouses:", e );
                }
                return warehouseMap;
        }

        @Override
        public Map<Long, String> getAllWarehouses() {
                Map<Long, String> warehouseMap = new HashMap<Long, String>();
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                        List<in.shop2020.model.v1.inventory.Warehouse> warehouses = inventoryClient.getAllWarehouses(true);

                        for(in.shop2020.model.v1.inventory.Warehouse w : warehouses) {
                                warehouseMap.put(w.getId(), w.getDisplayName());
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the warehouses:", e );
                }
                return warehouseMap;
        }

        @Override
        public long addItem(Item item) {
                long itemId = 0;
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        in.shop2020.model.v1.catalog.Item tItem = new in.shop2020.model.v1.catalog.Item();
                        tItem.setHsnCode(item.getHsnCode());
                        item.setQuantityStep(DEFAULTQUANTIYSTEP);
                        item.setMinimumBuyQuantity(DEFAULTMINBUYQTY);
                        item.setMaximumBuyQuantity(DEFAULTMAXBUYQTY);
                        setThriftItemParams(tItem, item);
                        itemId = catalogClient.addItem(tItem);
                        tItem = catalogClient.getItem(itemId);

                        Client catalogClientProd = new CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").getClient();
                        catalogClientProd.addItem(tItem);
                        Map<Long, VendorPricings> vendorPricings = item.getVendorPricesMap();
                        if(vendorPricings != null && !vendorPricings.isEmpty()) {
                                in.shop2020.model.v1.inventory.VendorItemPricing tVendorPricing;
                                for(VendorPricings v : vendorPricings.values()) {
                                        tVendorPricing = new in.shop2020.model.v1.inventory.VendorItemPricing();
                                        tVendorPricing.setVendorId(v.getVendorId());
                                        tVendorPricing.setItemId(itemId);
                                        tVendorPricing.setMop(v.getMop());
                                        tVendorPricing.setTransferPrice(v.getTransferPrice());
                                        tVendorPricing.setNlc(v.getNlc());
                                        tVendorPricing.setDealerPrice(v.getDealerPrice());
                                        inventoryClient.addVendorItemPricing(tVendorPricing);
                                }
                        }

                        Map<String, VendorItemMapping> vendorKeysMap = item.getVendorKeysMap();
                        if(vendorKeysMap != null && !vendorKeysMap.isEmpty()) {
                                in.shop2020.model.v1.inventory.VendorItemMapping tVendorMapping;
                                for(Entry<String, VendorItemMapping> e : vendorKeysMap.entrySet()) {
                                        tVendorMapping = new in.shop2020.model.v1.inventory.VendorItemMapping();
                                        VendorItemMapping v = e.getValue();
                                        tVendorMapping.setVendorId(v.getVendorId());
                                        tVendorMapping.setItemKey(v.getItemKey());
                                        tVendorMapping.setItemId(itemId);
                                        inventoryClient.addVendorItemMapping(e.getKey().substring(e.getKey().indexOf(Item.KEY_SEPARATOR)+1), tVendorMapping);
                                }
                        }

                        inventoryClient.updateItemStockPurchaseParams(itemId, item.getNumOfDaysStock(),
                                        item.getMinStockLevel());

                        if(item.getFreebieItemId()!=null && item.getFreebieItemId()!=0) {
                                in.shop2020.model.v1.catalog.FreebieItem freebieItem = 
                                        new in.shop2020.model.v1.catalog.FreebieItem();
                                freebieItem.setItemId(itemId);
                                freebieItem.setFreebieItemId(item.getFreebieItemId());
                                catalogClient.addOrUpdateFreebieForItem(freebieItem);
                        }

                } catch (Exception e) {
                        logger.error("Error while adding an item: ", e);
                }
                return itemId;
        }

        @Override
        public long checkSimilarItem(String brand, String modelNumber, String modelName, String color) {

                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();
                        return catalogClient.checkSimilarItem(brand, modelNumber, modelName, color);
                } catch (Exception e) {
                        logger.error("Error while checking for a similar item: ", e);
                }
                return 0;
        }

        private void setThriftItemParams(in.shop2020.model.v1.catalog.Item tItem, Item item) {
                tItem.setId(tItem.getId());
                tItem.setProductGroup(item.getProductGroup());
                tItem.setBrand(item.getBrand());
                tItem.setModelName(item.getModelName());
                tItem.setModelNumber(item.getModelNumber());
                tItem.setColor(item.getColor());
                tItem.setShowSellingPrice(item.isShowSellingPrice());
                tItem.setHoldOverride(item.isHoldOverride());
                tItem.setStatus_description(item.getItemStatusDesc());
                tItem.setComments(item.getComments());

                if(item.getMrp() != null) {
                        tItem.setMrp(item.getMrp());
                }

                if(item.getCatalogItemId() != null) {
                        tItem.setCatalogItemId(item.getCatalogItemId());
                }

                if(item.getSellingPrice() != null) {
                        tItem.setSellingPrice(item.getSellingPrice());
                }

                if(item.getWeight() != null) {
                        tItem.setWeight(item.getWeight());
                }

                if(item.getExpectedDelay() != null) {
                        tItem.setExpectedDelay(item.getExpectedDelay());
                }

                tItem.setIsWarehousePreferenceSticky(item.isWarehouseStickiness());

                if(item.getPreferredVendor() != null) {
                        tItem.setPreferredVendor(item.getPreferredVendor());
                }
                tItem.setPreferredInsurer(item.getPreferredInsurer());

                if(item.getAsin() != null) {
                        tItem.setAsin(item.getAsin());
                }
                if(item.getHoldInventory()!= null) {
                        tItem.setHoldInventory(item.getHoldInventory());
                }
                else{
                        tItem.setHoldInventory(0);
                }       
                if(item.getDefaultInventory()!=null){
                        tItem.setDefaultInventory(item.getDefaultInventory());
                }
                else{
                        tItem.setDefaultInventory(0);
                }
                tItem.setBestDealText(item.getBestDealsText());
                tItem.setBestDealsDetailsText(item.getBestDealsDetailsText());
                tItem.setBestDealsDetailsLink(item.getBestDealsDetailsLink());
                if(item.getBestDealsValue() != null) {
                        tItem.setBestDealValue(item.getBestDealsValue());
                }

                if(item.getBestSellingRank() != null) {
                        tItem.setBestSellingRank(item.getBestSellingRank());
                }

                tItem.setDefaultForEntity(item.isDefaultForEntity());
                tItem.setRisky(item.isRisky());
                tItem.setHasItemNo(item.isHasItemNo());

                if(item.isItemType()) {
                        tItem.setType(ItemType.SERIALIZED);
                }
                else {
                        tItem.setType(ItemType.NON_SERIALIZED);
                }

                if(item.getStartDate() != null) {
                        tItem.setStartDate(item.getStartDate());
                }

                if(item.getExpectedArrivalDate() != null) {
                        tItem.setExpectedArrivalDate(item.getExpectedArrivalDate());
                } else {
                        tItem.unsetComingSoonStartDate();
                        tItem.unsetExpectedArrivalDate();
                        if(status.COMING_SOON.equals(tItem.getItemStatus())){
                                tItem.setItemStatus(status.CONTENT_COMPLETE);
                                tItem.setStatus_description("Content generation completed");
                        }
                }

                if(item.getComingSoonStartDate() != null) {
                        tItem.setComingSoonStartDate(item.getComingSoonStartDate());
                } else {
                        tItem.unsetComingSoonStartDate();
                }

                if(item.getRetireDate() != null) {
                        tItem.setRetireDate(item.getRetireDate());
                }

                tItem.setUpdatedOn(Calendar.getInstance().getTimeInMillis());
                tItem.setPackQuantity(item.getPackQuantity());
                tItem.setQuantityStep(item.getQuantityStep());
                tItem.setMinimumBuyQuantity(item.getMinimumBuyQuantity());
                tItem.setMaximumBuyQuantity(item.getMaximumBuyQuantity());
        }

        @Override
        public void pauseItem(long itemId) {
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        catalogClient.changeItemStatus(itemId, Calendar.getInstance().getTimeInMillis(), status.PAUSED);
                } catch (Exception e) {
                        logger.error("Error while pausing the item: " + itemId, e);
                }

        }

        @Override
        public void markInProcess(long itemId) {
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        catalogClient.changeItemStatus(itemId, Calendar.getInstance().getTimeInMillis(), status.IN_PROCESS);
                } catch (Exception e) {
                        logger.error("Error while marking in-process the item: " + itemId, e);
                }
        }

        @Override
        public void phaseoutItem(long itemId) {
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        catalogClient.changeItemStatus(itemId, Calendar.getInstance().getTimeInMillis(), status.PHASED_OUT);
                } catch (Exception e) {
                        logger.error("Error while phasing out the item: " + itemId, e);
                }
        }

        @Override
        public void activateItem(long itemId) {
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        catalogClient.changeItemStatus(itemId, Calendar.getInstance().getTimeInMillis(), status.ACTIVE);
                } catch (Exception e) {
                        logger.error("Error while activating the item: " + itemId, e);
                }
        }

        @Override
        public boolean changeItemRiskyFlag(long itemId, boolean risky) {
                try {
                        logger.info("Updating risky flag for item id: " + itemId + " to " + risky);
                        // Initialize client for staging server
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        // Initialize client for production server
                        CatalogClient catalogServiceClient_Prod = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
                                        ConfigClientKeys.catalog_service_server_port.toString());
                        Client catalogClient_Prod = catalogServiceClient_Prod.getClient();
                        catalogClient.changeItemRiskyFlag(itemId, risky);

                        try{
                                catalogClient_Prod.changeItemRiskyFlag(itemId, risky);
                        }catch(Exception e){
                                logger.error("Error while updating item's risky flag on production", e);
                                // If not able to change risky flag on production, revert on staging and return false (to show error to user).
                                catalogClient.changeItemRiskyFlag(itemId, !risky);        
                                return false;
                        }
                } catch (Exception e) {
                        logger.error("Error while updating item's risky flag on staging", e);
                        return false;
                }
                return true;
        }


        /**
         * Retuns list of Items filtered by category (column is product_group in catalog.item table)
         * This list is used to generate master sheet (excel sheet)
         * @param category
         * @param brand
         * @return
         */
        public List<Item> getItemsForMasterSheet(String category, String brand) {
                List<Item> itemList = new ArrayList<Item>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getItemsForMasterSheet(category, brand);

                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                List<in.shop2020.model.v1.inventory.VendorItemPricing> vip = inventoryClient.getAllItemPricing(thriftItem.getId());
                                /*List<in.shop2020.model.v1.inventory.VendorItemMapping> vim = inventoryClient.getVendorItemMappings(thriftItem.getId());
                                List<in.shop2020.model.v1.catalog.SourceItemPricing> sip = catalogClient.getAllSourcePricing(thriftItem.getId());*/
                                Item item = getItemFromThriftItem(thriftItem, vip, null, null, null, null, null, null, null, null);
                                item.setDealPrice(thriftItem.getDealPrice());
                                itemList.add(item);
                        }
                } catch (Exception e) {
                        logger.error("Error while getting items by category: " + category, e);
                }
                Collections.sort(itemList, new ItemsComparator());
                return itemList;
        }

        @Override
        public String updateItemOnProduction(Item item) {
                if(!canPushToProduction()) {
                        // If we can't push to production, then return that message to user
                        // else move forward with update.
                        return "Maximum push to production count reached for today";
                }
                List<Long> itemIds = item.getSameItemsWithDifferentColors();
                List<Item> items = new ArrayList<Item>();
                items.add(item);
                for(Long itemId : itemIds) {
                        try {
                                CatalogClient catalogServiceClient = new CatalogClient();
                                Client catalogClient = catalogServiceClient.getClient();
                                InventoryClient inventoryServiceClient = new InventoryClient();
                                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                                in.shop2020.model.v1.catalog.Item thriftItem = catalogClient.getItem(itemId);
                                in.shop2020.model.v1.catalog.PrivateDeal tPrivateDeal = catalogClient.getPrivateDealDetails(itemId);
                                List<in.shop2020.model.v1.inventory.VendorItemPricing> vip = inventoryClient.getAllItemPricing(thriftItem.getId());
                                List<in.shop2020.model.v1.inventory.VendorItemMapping> vim = inventoryClient.getVendorItemMappings(thriftItem.getId());
                                List<in.shop2020.model.v1.catalog.SourceItemPricing> sip = catalogClient.getAllSourcePricing(thriftItem.getId());
                                items.add(getItemFromThriftItem(thriftItem, vip, vim, sip, null, null, null, null, null, null,null,tPrivateDeal));
                        } catch (Exception e) {
                                logger.error("Could not fetch item for : " + itemId, e);
                                return "Could not push to production. No item got pushed.";
                        }
                }
                
                
                for (Item it : items) {
                        logger.info("Update item on production call, Item Id: " + it.getId());

                        try{
                                CatalogClient catalogServiceClient_Prod = new CatalogClient( 
                                                ConfigClientKeys.catalog_service_server_host_prod.toString(),
                                                ConfigClientKeys.catalog_service_server_port.toString());

                                Client catalogClient_Prod = catalogServiceClient_Prod.getClient();
                                
                                CatalogClient catalogServiceClient = new CatalogClient();
                                Client catalogClient = catalogServiceClient.getClient();

                                in.shop2020.model.v1.catalog.Item tItem = catalogClient_Prod.getItem(it.getId());

                                InventoryClient inventoryServiceClient = new InventoryClient();
                                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                                if(it.getMrp() != null) {
                                        tItem.setMrp(it.getMrp());
                                }

                                if(it.getSellingPrice() != null) {
                                        tItem.setSellingPrice(it.getSellingPrice());
                                }
                                
                                tItem.setPackQuantity(it.getPackQuantity());
                                tItem.setQuantityStep(it.getQuantityStep());
                                tItem.setMinimumBuyQuantity(it.getMinimumBuyQuantity());
                                tItem.setMaximumBuyQuantity(it.getMaximumBuyQuantity());

                                tItem.setBestDealText(it.getBestDealsText());

                                if (it.getItemStatusValue()  == ItemStatus.ACTIVE.getValue() || it.getItemStatusValue()  == ItemStatus.PAUSED.getValue()) {
                                        tItem.setItemStatus(status.findByValue(it.getItemStatusValue()));
                                        tItem.setStartDate(it.getStartDate());
                                }
                                long rItemId;
                                if((rItemId = catalogClient_Prod.updateItem(tItem)) != it.getId()) {
                                        logger.error("Error updating item on production, returned Item Id: " + rItemId);
                                        return "Error updating item prices on production";
                                }
                                
                                
                                List<in.shop2020.model.v1.catalog.BulkItemPricing> t_bulkItemsPricing = catalogClient.getBulkPricingByItemId(it.getId());
                                if (!catalogClient_Prod.updateBulkPricesOnProduction(it.getId(), t_bulkItemsPricing)){
                                        return "Bulk prices updation error";
                                }
                                
                                if(it.getFreebieItemId() !=null && it.getFreebieItemId()!=0) {
                                        in.shop2020.model.v1.catalog.FreebieItem freebieItem = new in.shop2020.model.v1.catalog.FreebieItem();
                                        freebieItem.setItemId(it.getId());
                                        freebieItem.setFreebieItemId(it.getFreebieItemId());
                                        catalogClient_Prod.addOrUpdateFreebieForItem(freebieItem);
                                }
                                logger.info("Successfully updated item: " + it.getId());

                                StringBuilder sb = new StringBuilder();

                                Map<Long, VendorPricings> vendorPricings = it.getVendorPricesMap();
                                if(vendorPricings != null && !vendorPricings.isEmpty()) {
                                        in.shop2020.model.v1.inventory.VendorItemPricing tVendorPricing;
                                        for(VendorPricings v : vendorPricings.values()) {
                                                tVendorPricing = new in.shop2020.model.v1.inventory.VendorItemPricing();
                                                tVendorPricing.setVendorId(v.getVendorId());
                                                tVendorPricing.setItemId(it.getId());
                                                tVendorPricing.setMop(v.getMop());
                                                tVendorPricing.setTransferPrice(v.getTransferPrice());
                                                tVendorPricing.setNlc(v.getNlc());
                                                tVendorPricing.setDealerPrice(v.getDealerPrice());
                                                inventoryClient.addVendorItemPricing(tVendorPricing);
                                                logger.info("VendorItemPricing updated. " + tVendorPricing.toString());
                                                sb.append("[VId:" + v.getVendorId() + ",MOP=" + v.getMop() + ",TP=" + v.getTransferPrice() + ",NLC= " +v.getNlc() + ",DP=" + v.getDealerPrice() + "], ");
                                        }
                                }

                                Map<String, VendorItemMapping> vendorMappings = it.getVendorKeysMap();
                                if(vendorMappings != null && !vendorMappings.isEmpty()) {
                                        in.shop2020.model.v1.inventory.VendorItemMapping tVendorMapping;
                                        for(VendorItemMapping vendorItemMapping : vendorMappings.values()) {
                                                tVendorMapping = new in.shop2020.model.v1.inventory.VendorItemMapping();
                                                tVendorMapping.setVendorId(vendorItemMapping.getVendorId());
                                                tVendorMapping.setItemId(it.getId());
                                                tVendorMapping.setItemKey(vendorItemMapping.getItemKey());
                                                inventoryClient.addVendorItemMapping(vendorItemMapping.getItemKey(), tVendorMapping);
                                                logger.info("VendorItemMapping updated. " + tVendorMapping.toString());
                                                sb.append("[VId:" + vendorItemMapping.getVendorId() + ",ItemKey=" + vendorItemMapping.getItemKey() + "], ");
                                        }
                                }

                                Map<Long, SourcePricings> sourcePricings = it.getSourcePricesMap();
                                if(sourcePricings != null && !sourcePricings.isEmpty()){
                                        in.shop2020.model.v1.catalog.SourceItemPricing tSourcePricing;
                                        for(SourcePricings s : sourcePricings.values()){
                                                tSourcePricing = new in.shop2020.model.v1.catalog.SourceItemPricing();
                                                tSourcePricing.setSourceId(s.getSourceId());
                                                tSourcePricing.setItemId(it.getId());
                                                tSourcePricing.setMrp(s.getMrp());
                                                tSourcePricing.setSellingPrice(s.getSellingPrice());
                                                catalogClient_Prod.addSourceItemPricing(tSourcePricing);
                                                logger.info("SourceItemPricing updated. " + tSourcePricing.toString());
                                                sb.append("[SId:" + s.getSourceId() + ",MRP=" + s.getMrp() + ",SP=" + s.getSellingPrice() + "], ");
                                        }
                                }
                                pushToProdLogger.info("Id=" + it.getId() + ",MRP=" + it.getMrp() + ",SP=" + " " + it.getSellingPrice() + sb.toString());
                                in.shop2020.model.v1.catalog.PrivateDeal privateDeal = new in.shop2020.model.v1.catalog.PrivateDeal(); 
                                privateDeal.setItem_id(item.getId());
                                privateDeal.setDealFreebieItemId(item.getPrivateDeal().getDealFreebieItemId());
                                privateDeal.setDealPrice(item.getPrivateDeal().getDealPrice());
                                privateDeal.setDealText(item.getPrivateDeal().getDealText());
                                privateDeal.setDealFreebieOption(item.getPrivateDeal().getDealFreebieOption());
                                privateDeal.setDealTextOption(item.getPrivateDeal().getDealTextOption());
                                privateDeal.setEndDate(item.getPrivateDeal().getEndDate() == null ? 0 : item.getPrivateDeal().getEndDate());
                                privateDeal.setStartDate(item.getPrivateDeal().getStartDate() == null ? 0  : item.getPrivateDeal().getStartDate());
                                privateDeal.setIsCod(item.getPrivateDeal().isCod());
                                privateDeal.setRank(item.getPrivateDeal().getRank());
                                privateDeal.setIsActive(item.getPrivateDeal().isActive());
                                if(privateDeal.getDealPrice() > 0 && privateDeal.getEndDate()!=0 && privateDeal.getStartDate()!=0){
                                        logger.info("Updating Private deal: " + item.getId());
                                        logger.info("Deal Price "+privateDeal.getDealPrice());
                                        logger.info("Deal Start Date "+privateDeal.getStartDate());
                                        logger.info("Deal End Date "+privateDeal.getEndDate());
                                        logger.info("Has COD on deal: " + privateDeal.isIsCod());
                                        logger.info("Response" + catalogClient_Prod.addOrUpdatePrivateDeal(privateDeal));
                                        logger.info("Updated Private deal: " + item.getId());
                                }
                                else{
                                        logger.info("Skipping Private deal: " + item.getId());
                                        logger.info("Deal Price "+privateDeal.getDealPrice());
                                        logger.info("Deal Start Date "+privateDeal.getStartDate());
                                        logger.info("Deal End Date "+privateDeal.getEndDate());
                                }

                        } catch (Exception e) {
                                logger.error("Error while updating prices on production", e);
                                return "Error while updating all prices on production. Some of the prices may not have been  updated";
                        }
                }

                try {
                        ContentClient contentServiceClient = new ContentClient();
                        ContentService.Client contentClient = contentServiceClient.getClient();

                        contentClient.pushContentToProduction(items.get(0).getCatalogItemId());
                } catch (TTransportException e) {
                        logger.error("Error while establishing connection to the content server", e);
                        return "Error generating content. Prices updated successfully.";
                } catch (TException e) {
                        logger.error("Error while pushing content to production", e);
                        return "Error generating content. Prices updated successfully.";
                } catch (ContentServiceException e) {
                        logger.error("Error while pushing content to production", e);
                        return "Error generating content. Prices updated successfully.";
                }

                return "Prices updated and content generated successfully";
        }

        /**
         * Returns list of items with a particular status.
         * @param st
         * @return
         */
        private List<Item> getItemsByStatus(status st, int start, int limit) {
                List<Item> itemList = new ArrayList<Item>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Item> thriftItems = catalogClient.getAllItemsByStatusInRange(st, start, limit);

                        for(in.shop2020.model.v1.catalog.Item thriftItem : thriftItems) {
                                itemList.add(getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null, null, null));
                        }
                } catch (Exception e) {
                        logger.error("Error while getting items by status: " + st, e);
                }
                return itemList;
        }

        /**
         * Creates a new Item object and populates its attributes from thrift item passed as parameter.
         * Also creates a Map each for VendorItemPricing, VendorItemMapping, SourceItemPricing and SimilarItems and adds these maps to the
         * new Item object.
         * @param thriftItem
         * @param tVendorPricings
         * @param tVendorMappings
         * @param tSourceMappings
         * @param tSimilarItems
         * @param tVoucherMappings
         * @param stockPurchaseParams 
         * @return item object with attributes copied from thrift item object.
         */
        private Item getItemFromThriftItem(in.shop2020.model.v1.catalog.Item thriftItem, 
                        List<in.shop2020.model.v1.inventory.VendorItemPricing> tVendorPricings, 
                        List<in.shop2020.model.v1.inventory.VendorItemMapping> tVendorMappings,
                        List<in.shop2020.model.v1.catalog.SourceItemPricing> tSourceMappings,
                        List<in.shop2020.model.v1.catalog.Item> tSimilarItems, 
                        in.shop2020.model.v1.inventory.ItemInventory tItemInventory, 
                        List<in.shop2020.model.v1.catalog.VoucherItemMapping> tVoucherMappings, 
                        ItemStockPurchaseParams tStockPurchaseParams, Map<Long,String> saleHistory, Long freebieItemId){

                Map<String, VendorItemMapping> vItemMap = new HashMap<String, VendorItemMapping>();
                VendorItemMapping vItemMapping;
                if(tVendorMappings != null) {
                        for(in.shop2020.model.v1.inventory.VendorItemMapping vim : tVendorMappings) {
                                vItemMapping = new VendorItemMapping();
                                vItemMapping.setVendorId(vim.getVendorId());
                                vItemMapping.setItemKey(vim.getItemKey());
                                vItemMap.put(vItemMapping.getVendorId() + Item.KEY_SEPARATOR + vim.getItemKey(), vItemMapping);
                        }
                }

                Map<Long, VendorPricings> vendorPricingMap = new HashMap<Long, VendorPricings>();
                VendorPricings vPricings;
                if(tVendorPricings != null) {
                        for(in.shop2020.model.v1.inventory.VendorItemPricing vip : tVendorPricings) {
                                vPricings = new VendorPricings();
                                vPricings.setVendorId(vip.getVendorId());
                                vPricings.setMop(vip.getMop());
                                vPricings.setDealerPrice(vip.getDealerPrice());
                                vPricings.setTransferPrice(vip.getTransferPrice());
                                vPricings.setNlc(vip.getNlc());
                                vendorPricingMap.put(vPricings.getVendorId(), vPricings);
                        }
                }

                Map<Long, SourcePricings> sourcePricingMap = new HashMap<Long, SourcePricings>();
                SourcePricings sPricings;
                if(tSourceMappings != null) {
                        for(in.shop2020.model.v1.catalog.SourceItemPricing sip : tSourceMappings) {
                                sPricings = new SourcePricings();
                                sPricings.setSourceId(sip.getSourceId());
                                sPricings.setMrp(sip.getMrp());
                                sPricings.setSellingPrice(sip.getSellingPrice());
                                sourcePricingMap.put(sPricings.getSourceId(), sPricings);
                        }
                }

                Map<Long, Item> SimilarItemslist = new HashMap<Long, Item>();
                Item sItems;
                if(tSimilarItems != null) {
                        for(in.shop2020.model.v1.catalog.Item sit : tSimilarItems) {
                                sItems = new Item();
                                sItems.setCatalogItemId(sit.getCatalogItemId());
                                sItems.setProductGroup(sit.getProductGroup());
                                sItems.setBrand(sit.getBrand());
                                sItems.setModelNumber(sit.getModelNumber());
                                sItems.setModelName(sit.getModelName());
                                sItems.setContentCategory(CategoryManager.getCategoryManager().getCategoryLabel(sit.getCategory()));
                                SimilarItemslist.put(sit.getCatalogItemId(), sItems);
                        }
                }

                Map<Long, ItemInventory> itemInventoryMap = new HashMap<Long, ItemInventory>();
                ItemInventory warehousedata;
                if(tItemInventory != null) {
                        Map<Long, Long> availabilityMap = tItemInventory.getAvailability();
                        Map<Long, Long> reservedMap = tItemInventory.getReserved();
                        Map<Long, Long> heldMap = tItemInventory.getHeld();
                        for(Entry<Long, Long> availability : availabilityMap.entrySet()) {
                                Map<Integer, Long> heldInventoryMap = new HashMap<Integer, Long>();
                                warehousedata = new ItemInventory();
                                warehousedata.setWarehouseId(availability.getKey());
                                warehousedata.setAvailability(availability.getValue());
                                warehousedata.setReserved(reservedMap.get(availability.getKey()));
                                warehousedata.setHeld(heldMap.get(availability.getKey()));
                                try {
                                        if(warehousedata.getHeld()>0) {
                                                InventoryService.Client inventoryClient = new InventoryClient().getClient();
                                                heldInventoryMap = inventoryClient.getHeldInventoryMapForItem(thriftItem.getId(), availability.getKey());
                                        }
                                        if(heldInventoryMap.size()>0) {
                                                for(Integer source : heldInventoryMap.keySet()) {
                                                        switch(source) {
                                                        case HOMESHOP18SOURCE: warehousedata.setHomeshop18Held(heldInventoryMap.get(source));
                                                        break;
                                                        case EBAYSOURCE: warehousedata.setEbayHeld(heldInventoryMap.get(source));
                                                        break;
                                                        case SNAPDEALSOURCE: warehousedata.setSnapdealHeld(heldInventoryMap.get(source));
                                                        break;
                                                        case FLIPKARTSOURCE: warehousedata.setFlipkartHeld(heldInventoryMap.get(source));
                                                        }
                                                }
                                        }
                                } catch (Exception e) {
                                        logger.error("Error in getting data from holdInventoryDetail for itemId " + thriftItem.getId() + 
                                                        " and warehouse " +availability.getKey());
                                }
                                itemInventoryMap.put(warehousedata.getWarehouseId(), warehousedata);
                        }
                }
                else {
                        itemInventoryMap = null;
                }

                Map<String, VoucherItemMapping> voucherMap = new HashMap<String, VoucherItemMapping>();
                VoucherItemMapping voucher;
                if(tVoucherMappings != null) {
                        for(in.shop2020.model.v1.catalog.VoucherItemMapping tvoucher : tVoucherMappings) {
                                voucher = new VoucherItemMapping(tvoucher.getAmount(), VoucherType.findByValue((int) tvoucher.getVoucherType()).name());
                                voucherMap.put(VoucherType.findByValue((int) tvoucher.getVoucherType()).name(), voucher);
                        }
                }

                in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams stockPurchaseParams = 
                        new in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams();
                if(tStockPurchaseParams != null) {
                        stockPurchaseParams.setItem_id(tStockPurchaseParams.getItem_id());
                        stockPurchaseParams.setMinStockLevel(tStockPurchaseParams.getMinStockLevel());
                        stockPurchaseParams.setNumOfDaysStock(tStockPurchaseParams.getNumOfDaysStock());
                }

                Item item = new Item(thriftItem.getId(),
                                thriftItem.getProductGroup(),
                                thriftItem.getBrand(),
                                thriftItem.getModelNumber(),
                                thriftItem.getModelName(),
                                thriftItem.getColor(),
                                CategoryManager.getCategoryManager().getCategoryLabel(thriftItem.getCategory()),
                                thriftItem.getCategory(),
                                thriftItem.getComments(),
                                thriftItem.getCatalogItemId(),
                                thriftItem.getFeatureId(),
                                thriftItem.getFeatureDescription(),
                                thriftItem.isSetMrp() ? thriftItem.getMrp() : null,
                                                thriftItem.isSetSellingPrice() ? thriftItem.getSellingPrice() : null,
                                                                thriftItem.isSetWeight() ? thriftItem.getWeight() : null,
                                                                                thriftItem.getAddedOn(),
                                                                                thriftItem.getStartDate(),
                                                                                thriftItem.isSetComingSoonStartDate() ? thriftItem.getComingSoonStartDate() : null ,
                                                                                                thriftItem.isSetExpectedArrivalDate() ? thriftItem.getExpectedArrivalDate() : null ,
                                                                                                                thriftItem.getRetireDate(),
                                                                                                                thriftItem.getUpdatedOn(),
                                                                                                                thriftItem.getItemStatus().name(),
                                                                                                                thriftItem.getItemStatus().getValue(),
                                                                                                                thriftItem.getStatus_description(),
                                                                                                                thriftItem.getBestDealText(),
                                                                                                                thriftItem.getBestDealsDetailsText(),
                                                                                                                thriftItem.getBestDealsDetailsLink(),
                                                                                                                thriftItem.isSetBestDealValue() ? thriftItem.getBestDealValue() : null,
                                                                                                                                thriftItem.isSetBestSellingRank() ? thriftItem.getBestSellingRank() : null,
                                                                                                                                                thriftItem.isDefaultForEntity(),
                                                                                                                                                thriftItem.isRisky(),
                                                                                                                                                thriftItem.isSetExpectedDelay() ? thriftItem.getExpectedDelay() : null,
                                                                                                                                                                thriftItem.isIsWarehousePreferenceSticky(),
                                                                                                                                                                thriftItem.isHasItemNo(),
                                                                                                                                                                ItemType.SERIALIZED.equals(thriftItem.getType()),
                                                                                                                                                                thriftItem.isSetShowSellingPrice() ? thriftItem.isShowSellingPrice() : false,
                                                                                                                                                                                thriftItem.isHoldOverride(),
                                                                                                                                                                                thriftItem.isSetPreferredVendor() ? thriftItem.getPreferredVendor() : null,
                                                                                                                                                                                                thriftItem.isSetPreferredInsurer() ? thriftItem.getPreferredInsurer() : null,           
                                                                                                                                                                                                                itemInventoryMap,
                                                                                                                                                                                                                vendorPricingMap,
                                                                                                                                                                                                                vItemMap,
                                                                                                                                                                                                                sourcePricingMap,
                                                                                                                                                                                                                SimilarItemslist,
                                                                                                                                                                                                                voucherMap, 
                                                                                                                                                                                                                stockPurchaseParams.getNumOfDaysStock(), 
                                                                                                                                                                                                                stockPurchaseParams.getMinStockLevel(), 
                                                                                                                                                                                                                saleHistory, 
                                                                                                                                                                                                                freebieItemId,
                                                                                                                                                                                                                thriftItem.getAsin(),
                                                                                                                                                                                                                thriftItem.getHoldInventory(),
                                                                                                                                                                                                                thriftItem.getDefaultInventory());
                return item;
        }

        /**
         * 
         * @return True if push to production count is less than maximum allowed.
         */
        private boolean canPushToProduction() {
                int count = getPushToProdCount(logFile);
                return count < maxCount;
        }

        /**
         * If this is the first attempt to push to production for current date, returns 0
         * else reads number of lines from daily rolling log file to get the count.
         * @return push to production count for current date
         */
        private int getPushToProdCount(String logfile) {
                // logfile is "/var/log/services/pushToProductionCount/pushToProd.log"
                // this should also be set in log4j.properties
                int lineCount = 0;
                DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                Date currentDate = Calendar.getInstance().getTime();
                if(pushToProdDate == null ||  !dateFormat.format(pushToProdDate).equals(dateFormat.format(currentDate))) {
                        pushToProdDate = currentDate;
                        return lineCount;
                }
                try {
                        BufferedReader br = new BufferedReader(new FileReader(logfile));
                        while (br.readLine() != null) {
                                lineCount++;
                        }
                } catch (IOException e) {
                        logger.error("Error while reading the log file", e);
                }
                return lineCount;
        }

        @Override
        public boolean deleteSimilarItem(long itemId, long catalogItemId) {
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        return catalogClient.deleteSimilarItem(itemId, catalogItemId);

                }catch(Exception e){
                        logger.error("Error while deleting the SimilarItems for: " + itemId, e);
                }
                return false;
        }

        @Override
        public Item addSimilarItem(long itemId, long catalogItemId) {
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();
                        in.shop2020.model.v1.catalog.Item thriftItem = catalogClient.addSimilarItem(itemId, catalogItemId);;

                        return getItemFromThriftItem(thriftItem, null, null, null, null, null, null, null, null, null,null,null);
                }catch(Exception e){
                        logger.error("Error while adding the SimilarItems for: " + itemId, e);
                }
                return null;
        }

        @Override
        public Map<Long, ItemInventory> getProdItemInventory(long itemId) {
                try {
                        // Initialize client for production server
                        CatalogClient catalogServiceClient_Prod = new CatalogClient(ConfigClientKeys.catalog_service_server_host_prod.toString(),
                                        ConfigClientKeys.catalog_service_server_port.toString());
                        Client catalogClient_Prod = catalogServiceClient_Prod.getClient();
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(itemId);

                        Map<Long, ItemInventory> itemInventoryMap = new HashMap<Long, ItemInventory>();
                        ItemInventory warehousedata;
                        if(thriftItemInventory != null) {
                                Map<Long, Long> availabilityMap = thriftItemInventory.getAvailability();
                                Map<Long, Long> reservedMap = thriftItemInventory.getReserved();
                                Map<Long, Long> heldMap = thriftItemInventory.getHeld();
                                for(Entry<Long, Long> availability : availabilityMap.entrySet()) {
                                        Map<Integer, Long> heldInventoryMap = new HashMap<Integer, Long>();
                                        warehousedata = new ItemInventory();
                                        warehousedata.setWarehouseId(availability.getKey());
                                        warehousedata.setAvailability(availability.getValue());
                                        warehousedata.setReserved(reservedMap.get(availability.getKey()));
                                        warehousedata.setHeld(heldMap.get(availability.getKey()));
                                        try {
                                                if(warehousedata.getHeld()>0) {
                                                        heldInventoryMap = inventoryClient.getHeldInventoryMapForItem(itemId, availability.getKey());
                                                }
                                                if(heldInventoryMap.size()>0) {
                                                        for(Integer source : heldInventoryMap.keySet()) {
                                                                switch(source) {
                                                                case HOMESHOP18SOURCE: warehousedata.setHomeshop18Held(heldInventoryMap.get(source));
                                                                break;
                                                                case EBAYSOURCE: warehousedata.setEbayHeld(heldInventoryMap.get(source));
                                                                break;
                                                                case SNAPDEALSOURCE: warehousedata.setSnapdealHeld(heldInventoryMap.get(source));
                                                                break;
                                                                case FLIPKARTSOURCE: warehousedata.setFlipkartHeld(heldInventoryMap.get(source));
                                                                }
                                                        }
                                                } 
                                        }catch (Exception e) {
                                                logger.error("Error in getting data from holdInventoryDetail for itemId " + itemId + 
                                                                " and warehouse " +availability.getKey());
                                        }
                                        itemInventoryMap.put(warehousedata.getWarehouseId(), warehousedata);
                                }
                        }
                        else {
                                itemInventoryMap = null;
                        }
                        return itemInventoryMap;
                } catch (Exception e) {
                        logger.error("Error while updating item's risky flag on staging", e);
                }
                return null;
        }

        @Override
        public boolean addAuthorizationLog(long itemId, String username, String message) {
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        return catalogClient.addAuthorizationLog(itemId, username, message);

                }catch(Exception e){
                        logger.error("Error while adding the event for: " + itemId, e);
                }
                return false;
        }

        @Override
        public Map<String, String> getConfigdataforPriceCompare() {
                Map<String, String> ConfigMap = new HashMap<String, String>();
                try {
                        ConfigMap.put("courier_cost_factor", ConfigClient.getClient().get(ConfigClientKeys.courier_cost_factor.toString()));
                        ConfigMap.put("courier_weight_factor", ConfigClient.getClient().get(ConfigClientKeys.courier_weight_factor.toString()));
                        ConfigMap.put("breakeven_divisor", ConfigClient.getClient().get(ConfigClientKeys.breakeven_divisor.toString()));
                        ConfigMap.put("breakeven_additon_factor", ConfigClient.getClient().get(ConfigClientKeys.breakeven_additon_factor.toString()));
                        ConfigMap.put("transfer_price_percentage", ConfigClient.getClient().get(ConfigClientKeys.transfer_price_percentage.toString()));
                        ConfigMap.put("transfer_price_factor", ConfigClient.getClient().get(ConfigClientKeys.transfer_price_factor.toString()));
                } catch(ConfigException ce) {
                        logger.error("Unable to connect to the config server. Setting sensible defaults.", ce);
                        ConfigMap.put("courier_cost_factor", "60");
                        ConfigMap.put("courier_weight_factor", "500");
                        ConfigMap.put("breakeven_divisor", "0.98");
                        ConfigMap.put("breakeven_additon_factor", "50");
                        ConfigMap.put("transfer_price_percentage", "2");
                        ConfigMap.put("transfer_price_factor", "50");
                }
                return ConfigMap;
        }

        @Override
        public List<String> getAllCategories() {
                List<String> categoryList = new ArrayList<String>();
                List<Long> parentCategoryIDs = Arrays.asList(new Long[] {(long) 0,(long) 10001,(long) 10009,(long) 10049});
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Category> categories = catalogClient.getAllCategories();

                        for(in.shop2020.model.v1.catalog.Category category : categories) {
                                if(!parentCategoryIDs.contains(category.getParent_category_id())){
                                        categoryList.add(category.getDisplay_name());
                                }
                                else{
                                        continue;
                                }
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the categories: ", e);
                }
                return categoryList;
        }

        @Override
        public Map<Long, String> getAllCategoriesMap() {
                Map<Long, String> categoryList = new TreeMap<Long, String>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        List<in.shop2020.model.v1.catalog.Category> categories = catalogClient.getAllCategories();

                        for(in.shop2020.model.v1.catalog.Category category : categories) {
                                if(category.getParent_category_id() != 10000l && category.getParent_category_id() != 0l){
                                        categoryList.put(category.getId(), category.getLabel());
                                }
                                else{
                                        continue;
                                }
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the categories: ", e);
                }
                return categoryList;
        }


        @Override
        public List<String> getAllBrands() {
                List<String> brandsList = new ArrayList<String>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        brandsList = catalogClient.getAllBrands();
                } catch (Exception e) {
                        logger.error("Error while getting all the categories: ", e);
                }
                return brandsList;
        }

        @Override
        public boolean deleteVoucher(Long catalogItemId, Long voucherType) {
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        return catalogClient.deleteVoucherForItem(catalogItemId, voucherType);

                }catch(Exception e){
                        logger.error("Error while deleting the Voucher for: " + catalogItemId, e);
                }
                return false;
        }

        @Override
        public boolean addVoucher(Long catalogItemId, Long voucherType, long voucherAmount) {
                try{
                        CatalogClient catalogServiceClient = new CatalogClient();
                        Client catalogClient = catalogServiceClient.getClient();

                        return catalogClient.addupdateVoucherForItem(catalogItemId, voucherType, voucherAmount);

                }catch(Exception e){
                        logger.error("Error while adding the Voucher for: " + catalogItemId, e);
                }
                return false;
        }
        @Override
        public Map<Long, String> getvoucherTypes() {
                Map<Long, String> voucherType = new HashMap<Long, String>();
                for(VoucherType voucher : VoucherType.values())
                {
                        voucherType.put((long) voucher.getValue(), voucher.name());
                }
                return voucherType;
        }

        @Override
        public boolean getConfigforentityIdMandatory() {
                try {
                        String entityId_mandatory = ConfigClient.getClient().get(ConfigClientKeys.entityId_mandatory.toString());
                        if (entityId_mandatory.equals("TRUE")) {
                                return true;
                        }
                } catch(ConfigException ce) {
                        logger.error("Unable to connect to the config server. Setting sensible defaults.", ce);
                }
                return false;
        }

        @Override
        public boolean checkEntityId(long entityId) {
                try {
                        CatalogClient catalogServiceClient = new CatalogClient(ConfigClientKeys.catalog_service_server_host_master.toString(), ConfigClientKeys.catalog_service_server_port.toString());
                        Client catalogClient = catalogServiceClient.getClient();
                        return catalogClient.isValidCatalogItemId(entityId);
                } catch (Exception e) {
                        logger.error("Error while checking for a Catalog Item Id: ", e);
                }
                return false;
        }

        @Override
        public String updateExpectedDelayOnProd(Item item) {
                try{
                        CatalogClient catalogServiceClient_Prod = new CatalogClient( 
                                        ConfigClientKeys.catalog_service_server_host_prod.toString(),
                                        ConfigClientKeys.catalog_service_server_port.toString());

                        Client catalogClient_Prod = catalogServiceClient_Prod.getClient();


                        in.shop2020.model.v1.catalog.Item tItem = catalogClient_Prod.getItem(item.getId());
                        if(item.getExpectedDelay() != null) {
                                tItem.setExpectedDelay(item.getExpectedDelay());
                                if(item.isItemType()) {
                                        tItem.setType(ItemType.SERIALIZED);
                                }
                                else {
                                        tItem.setType(ItemType.NON_SERIALIZED);
                                }
                                long rItemId;
                                if((rItemId = catalogClient_Prod.updateItem(tItem)) != item.getId()) {
                                        logger.error("Error updating item on production, returned Item Id: " + rItemId);
                                        return "Error updating expected delay on production";
                                }
                                InventoryClient inventoryServiceClient= new InventoryClient();
                                InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                                inventoryClient.clearItemAvailabilityCacheForItem(rItemId);
                                logger.info("Successfully updated item: " + item.getId());
                                return "Expected delay successfully updated on prod"; 
                        } else {
                                return "Error:expected delay should not be null";
                        }
                } catch (Exception e) {
                        logger.error("Error while updating expected delay on production", e);
                        return "Error while updating expected delay on production";
                }
        }

        @Override
        public Map<Long, String> getAllInsurers() {
                Map<Long, String> insurersMap = new HashMap<Long, String>();
                try {
                        CatalogClient catalogServiceClient = new CatalogClient();
                        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();

                        List<Insurer> insurers = catalogClient.getAllInsurers();

                        for(in.shop2020.model.v1.catalog.Insurer i : insurers) {
                                insurersMap.put(i.getId(), i.getName());
                        }
                } catch (Exception e) {
                        logger.error("Error while getting all the vendors: ", e);
                }
                return insurersMap;
        }

        private Item getItemFromThriftItem(in.shop2020.model.v1.catalog.Item thriftItem, 
                        List<in.shop2020.model.v1.inventory.VendorItemPricing> tVendorPricings, 
                        List<in.shop2020.model.v1.inventory.VendorItemMapping> tVendorMappings,
                        List<in.shop2020.model.v1.catalog.SourceItemPricing> tSourceMappings,
                        List<in.shop2020.model.v1.catalog.Item> tSimilarItems, 
                        in.shop2020.model.v1.inventory.ItemInventory tItemInventory, 
                        List<in.shop2020.model.v1.catalog.VoucherItemMapping> tVoucherMappings, 
                        ItemStockPurchaseParams tStockPurchaseParams, Map<Long,String> saleHistory, Long freebieItemId,Map<String,String> stateNameVatPercentageMap,in.shop2020.model.v1.catalog.PrivateDeal tPrivateDeal){

                Map<String, VendorItemMapping> vItemMap = new HashMap<String, VendorItemMapping>();
                VendorItemMapping vItemMapping;
                if(tVendorMappings != null) {
                        for(in.shop2020.model.v1.inventory.VendorItemMapping vim : tVendorMappings) {
                                vItemMapping = new VendorItemMapping();
                                vItemMapping.setVendorId(vim.getVendorId());
                                vItemMapping.setItemKey(vim.getItemKey());
                                vItemMap.put(vItemMapping.getVendorId() + Item.KEY_SEPARATOR + vim.getItemKey(), vItemMapping);
                        }
                }

                Map<Long, VendorPricings> vendorPricingMap = new HashMap<Long, VendorPricings>();
                VendorPricings vPricings;
                if(tVendorPricings != null) {
                        for(in.shop2020.model.v1.inventory.VendorItemPricing vip : tVendorPricings) {
                                vPricings = new VendorPricings();
                                vPricings.setVendorId(vip.getVendorId());
                                vPricings.setMop(vip.getMop());
                                vPricings.setDealerPrice(vip.getDealerPrice());
                                vPricings.setTransferPrice(vip.getTransferPrice());
                                vPricings.setNlc(vip.getNlc());
                                vendorPricingMap.put(vPricings.getVendorId(), vPricings);
                        }
                }

                Map<Long, SourcePricings> sourcePricingMap = new HashMap<Long, SourcePricings>();
                SourcePricings sPricings;
                if(tSourceMappings != null) {
                        for(in.shop2020.model.v1.catalog.SourceItemPricing sip : tSourceMappings) {
                                sPricings = new SourcePricings();
                                sPricings.setSourceId(sip.getSourceId());
                                sPricings.setMrp(sip.getMrp());
                                sPricings.setSellingPrice(sip.getSellingPrice());
                                sourcePricingMap.put(sPricings.getSourceId(), sPricings);
                        }
                }

                Map<Long, Item> SimilarItemslist = new HashMap<Long, Item>();
                Item sItems;
                if(tSimilarItems != null) {
                        for(in.shop2020.model.v1.catalog.Item sit : tSimilarItems) {
                                sItems = new Item();
                                sItems.setCatalogItemId(sit.getCatalogItemId());
                                sItems.setProductGroup(sit.getProductGroup());
                                sItems.setBrand(sit.getBrand());
                                sItems.setModelNumber(sit.getModelNumber());
                                sItems.setModelName(sit.getModelName());
                                sItems.setContentCategory(CategoryManager.getCategoryManager().getCategoryLabel(sit.getCategory()));
                                SimilarItemslist.put(sit.getCatalogItemId(), sItems);
                        }
                }

                Map<Long, ItemInventory> itemInventoryMap = new HashMap<Long, ItemInventory>();
                ItemInventory warehousedata;
                if(tItemInventory != null) {
                        Map<Long, Long> availabilityMap = tItemInventory.getAvailability();
                        Map<Long, Long> reservedMap = tItemInventory.getReserved();
                        Map<Long, Long> heldMap = tItemInventory.getHeld();
                        for(Entry<Long, Long> availability : availabilityMap.entrySet()) {
                                Map<Integer, Long> heldInventoryMap = new HashMap<Integer, Long>();
                                warehousedata = new ItemInventory();
                                warehousedata.setWarehouseId(availability.getKey());
                                warehousedata.setAvailability(availability.getValue());
                                warehousedata.setReserved(reservedMap.get(availability.getKey()));
                                warehousedata.setHeld(heldMap.get(availability.getKey()));
                                try {
                                        if(warehousedata.getHeld()>0) {
                                                InventoryService.Client inventoryClient = new InventoryClient().getClient();
                                                heldInventoryMap = inventoryClient.getHeldInventoryMapForItem(thriftItem.getId(), availability.getKey());
                                        }
                                        if(heldInventoryMap.size()>0) {
                                                for(Integer source : heldInventoryMap.keySet()) {
                                                        switch(source) {
                                                        case HOMESHOP18SOURCE: warehousedata.setHomeshop18Held(heldInventoryMap.get(source));
                                                        break;
                                                        case EBAYSOURCE: warehousedata.setEbayHeld(heldInventoryMap.get(source));
                                                        break;
                                                        case SNAPDEALSOURCE: warehousedata.setSnapdealHeld(heldInventoryMap.get(source));
                                                        break;
                                                        case FLIPKARTSOURCE: warehousedata.setFlipkartHeld(heldInventoryMap.get(source));
                                                        }
                                                }
                                        }
                                } catch (Exception e) {
                                        logger.error("Error in getting data from holdInventoryDetail for itemId " + thriftItem.getId() + 
                                                        " and warehouse " +availability.getKey());
                                }
                                itemInventoryMap.put(warehousedata.getWarehouseId(), warehousedata);
                        }
                }
                else {
                        itemInventoryMap = null;
                }

                Map<String, VoucherItemMapping> voucherMap = new HashMap<String, VoucherItemMapping>();
                VoucherItemMapping voucher;
                if(tVoucherMappings != null) {
                        for(in.shop2020.model.v1.catalog.VoucherItemMapping tvoucher : tVoucherMappings) {
                                voucher = new VoucherItemMapping(tvoucher.getAmount(), VoucherType.findByValue((int) tvoucher.getVoucherType()).name());
                                voucherMap.put(VoucherType.findByValue((int) tvoucher.getVoucherType()).name(), voucher);
                        }
                }

                in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams stockPurchaseParams = 
                        new in.shop2020.catalog.dashboard.shared.ItemStockPurchaseParams();
                if(tStockPurchaseParams != null) {
                        stockPurchaseParams.setItem_id(tStockPurchaseParams.getItem_id());
                        stockPurchaseParams.setMinStockLevel(tStockPurchaseParams.getMinStockLevel());
                        stockPurchaseParams.setNumOfDaysStock(tStockPurchaseParams.getNumOfDaysStock());
                }
                in.shop2020.catalog.dashboard.shared.PrivateDeal privateDeal=null;
                if(tPrivateDeal!=null){
                        privateDeal= new in.shop2020.catalog.dashboard.shared.PrivateDeal();
                        if(tPrivateDeal.isSetDealFreebieItemId()){
                                privateDeal.setDealFreebieItemId(tPrivateDeal.getDealFreebieItemId());
                        }
                        privateDeal.setItem_id(tPrivateDeal.getItem_id());
                        privateDeal.setDealPrice(tPrivateDeal.getDealPrice());
                        if(tPrivateDeal.isSetStartDate()){
                                privateDeal.setStartDate(tPrivateDeal.getStartDate());
                        }
                        else{
                                privateDeal.setStartDate(null);
                        }
                        if(tPrivateDeal.isSetEndDate()){
                                privateDeal.setEndDate(tPrivateDeal.getEndDate());
                        }
                        else{
                                privateDeal.setEndDate(null);
                        }
                        privateDeal.setRank(tPrivateDeal.getRank());
                        if(tPrivateDeal.isSetIsCod()){
                                privateDeal.setCod(tPrivateDeal.isIsCod());
                        }
                        else{
                                privateDeal.setCod(true);
                        }
                        if(tPrivateDeal.isSetDealFreebieOption()){
                                privateDeal.setDealFreebieOption(tPrivateDeal.getDealFreebieOption());
                        }
                        else{
                                privateDeal.setDealFreebieOption(1L);
                        }
                        if(tPrivateDeal.isSetDealText()){
                                privateDeal.setDealText(tPrivateDeal.getDealText());
                        }
                        else{
                                if(thriftItem.isSetBestDealText()){
                                        privateDeal.setDealText(thriftItem.getBestDealText());
                                }
                                else{
                                        privateDeal.setDealText("");
                                }
                        }
                        if(tPrivateDeal.isSetDealTextOption()){
                                privateDeal.setDealTextOption(tPrivateDeal.getDealTextOption());
                        }
                        else{
                                privateDeal.setDealTextOption(1L);
                        }
                        if(tPrivateDeal.isSetIsActive()){
                                privateDeal.setActive(tPrivateDeal.isIsActive());
                        }
                        else{
                                privateDeal.setActive(false);
                        }
                }
                Item item = new Item(thriftItem.getId(),
                                thriftItem.getProductGroup(),
                                thriftItem.getBrand(),
                                thriftItem.getModelNumber(),
                                thriftItem.getModelName(),
                                thriftItem.getColor(),
                                CategoryManager.getCategoryManager().getCategoryLabel(thriftItem.getCategory()),
                                thriftItem.getCategory(),
                                thriftItem.getComments(),
                                thriftItem.getCatalogItemId(),
                                thriftItem.getFeatureId(),
                                thriftItem.getFeatureDescription(),
                                thriftItem.isSetMrp() ? thriftItem.getMrp() : null,
                                                thriftItem.isSetSellingPrice() ? thriftItem.getSellingPrice() : null,
                                                                thriftItem.isSetWeight() ? thriftItem.getWeight() : null,
                                                                                thriftItem.getAddedOn(),
                                                                                thriftItem.getStartDate(),
                                                                                thriftItem.isSetComingSoonStartDate() ? thriftItem.getComingSoonStartDate() : null ,
                                                                                                thriftItem.isSetExpectedArrivalDate() ? thriftItem.getExpectedArrivalDate() : null ,
                                                                                                                thriftItem.getRetireDate(),
                                                                                                                thriftItem.getUpdatedOn(),
                                                                                                                thriftItem.getItemStatus().name(),
                                                                                                                thriftItem.getItemStatus().getValue(),
                                                                                                                thriftItem.getStatus_description(),
                                                                                                                thriftItem.getBestDealText(),
                                                                                                                thriftItem.getBestDealsDetailsText(),
                                                                                                                thriftItem.getBestDealsDetailsLink(),
                                                                                                                thriftItem.isSetBestDealValue() ? thriftItem.getBestDealValue() : null,
                                                                                                                                thriftItem.isSetBestSellingRank() ? thriftItem.getBestSellingRank() : null,
                                                                                                                                                thriftItem.isDefaultForEntity(),
                                                                                                                                                thriftItem.isRisky(),
                                                                                                                                                thriftItem.isSetExpectedDelay() ? thriftItem.getExpectedDelay() : null,
                                                                                                                                                                thriftItem.isIsWarehousePreferenceSticky(),
                                                                                                                                                                thriftItem.isHasItemNo(),
                                                                                                                                                                ItemType.SERIALIZED.equals(thriftItem.getType()),
                                                                                                                                                                thriftItem.isSetShowSellingPrice() ? thriftItem.isShowSellingPrice() : false,
                                                                                                                                                                                thriftItem.isHoldOverride(),
                                                                                                                                                                                thriftItem.isSetPreferredVendor() ? thriftItem.getPreferredVendor() : null,
                                                                                                                                                                                                thriftItem.isSetPreferredInsurer() ? thriftItem.getPreferredInsurer() : null,           
                                                                                                                                                                                                                itemInventoryMap,
                                                                                                                                                                                                                vendorPricingMap,
                                                                                                                                                                                                                vItemMap,
                                                                                                                                                                                                                sourcePricingMap,
                                                                                                                                                                                                                SimilarItemslist,
                                                                                                                                                                                                                voucherMap, 
                                                                                                                                                                                                                stockPurchaseParams.getNumOfDaysStock(), 
                                                                                                                                                                                                                stockPurchaseParams.getMinStockLevel(), 
                                                                                                                                                                                                                saleHistory, 
                                                                                                                                                                                                                freebieItemId,
                                                                                                                                                                                                                thriftItem.getAsin(),
                                                                                                                                                                                                                thriftItem.getHoldInventory(),
                                                                                                                                                                                                                thriftItem.getDefaultInventory(),stateNameVatPercentageMap,privateDeal, thriftItem.getPackQuantity(),
                                                                                                                                                                                                                thriftItem.getQuantityStep(),thriftItem.getMinimumBuyQuantity(),thriftItem.getMaximumBuyQuantity());
                return item;
        }

        @Override
        public Map<Long, Double> getVatRates(long itemId, long categoryId) {
                try {
                        Client catalogClient = new CatalogClient().getClient();
                        return catalogClient.getVatRates(itemId, categoryId);
                } catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not fetch vat rates");
                }
                return new HashMap<Long, Double>(); 
        }

        @Override
        public Map<Long, String> getAllStatesMap() {
                Map<Long, String> allStatesMap = new TreeMap<Long, String>();
                try {
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        Map<Long, StateInfo> stateMasterInfo = inventoryClient.getStateMaster();
                        for( Map.Entry<Long, StateInfo> si : stateMasterInfo.entrySet()){
                                allStatesMap.put(si.getKey(), si.getValue().getStateName());
                        }
                } catch (Exception e){
                        logger.info("Could not fetch States");
                        e.printStackTrace();
                }
                return allStatesMap;
        }

        @Override
        public boolean markPartiallyActive(long itemId, Long categoryId) {
                try {
                        Client catalogClient = new CatalogClient().getClient();
                        catalogClient.markPartiallyActive(itemId, categoryId);
                        Client catalogClientProd =  new CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").getClient();
                        catalogClientProd.markPartiallyActive(itemId, categoryId);
                        return true;
                } catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not update");
                }
                return false;
        }

        @Override
        public boolean updateItemStateVat(long itemId, List<in.shop2020.catalog.dashboard.shared.StateVat> svs) {
                logger.info("In update itemStateVat");
                try {
                        Map<Long, Double> stateVatMap = new HashMap<Long, Double>();
                        for(in.shop2020.catalog.dashboard.shared.StateVat sv : svs){
                                stateVatMap.put(sv.stateId, sv.vatRate);
                        }
                        Client catalogClient = new CatalogClient().getClient();
                        catalogClient.updateItemStateVat(itemId, stateVatMap);
                        Client catalogClientProd =  new CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").getClient();
                        catalogClientProd.updateItemStateVat(itemId, stateVatMap);
                        return true;
                } catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not update");
                        return false;
                }
        }

        public in.shop2020.catalog.dashboard.shared.BulkItemPricing addBulkPricingForItem(BulkItemPricing bulkItemPricing){
                try{
                        in.shop2020.model.v1.catalog.BulkItemPricing t_bulkItemPricing = new in.shop2020.model.v1.catalog.BulkItemPricing();
                        t_bulkItemPricing.setItem_id(bulkItemPricing.getItem_id());
                        t_bulkItemPricing.setPrice(bulkItemPricing.getPrice());
                        t_bulkItemPricing.setQuantity(bulkItemPricing.getQuantity());
                        Client catalogClient = new CatalogClient().getClient();
                        in.shop2020.model.v1.catalog.BulkItemPricing result =  catalogClient.addBulkPricingForItem(t_bulkItemPricing);
                        in.shop2020.catalog.dashboard.shared.BulkItemPricing bulkItemPricingObj = new in.shop2020.catalog.dashboard.shared.BulkItemPricing(result.getId(), result.getItem_id(), result.getQuantity(), result.getPrice());
                        return bulkItemPricingObj;
                }
                catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not add bulk pricing");
                        return null;
                }
        }

        public List<in.shop2020.catalog.dashboard.shared.BulkItemPricing> getBulkPricingByItemId(long itemId){
                try{
                        List<in.shop2020.catalog.dashboard.shared.BulkItemPricing> listBulkItemPricingObj = new ArrayList<in.shop2020.catalog.dashboard.shared.BulkItemPricing>();
                        Client catalogClient = new CatalogClient().getClient();
                        List<in.shop2020.model.v1.catalog.BulkItemPricing> t_bulkItemsPricing = catalogClient.getBulkPricingByItemId(itemId);
                        for (in.shop2020.model.v1.catalog.BulkItemPricing result : t_bulkItemsPricing){
                                in.shop2020.catalog.dashboard.shared.BulkItemPricing bulkItemPricingObj = new in.shop2020.catalog.dashboard.shared.BulkItemPricing(result.getId(), result.getItem_id(), result.getQuantity(), result.getPrice());
                                listBulkItemPricingObj.add(bulkItemPricingObj);
                        }
                        return listBulkItemPricingObj;
                }
                catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not get bulk pricing");
                        return null;
                }
        }

        public boolean deleteBulkPricingForItemById(long id){
                try{
                        Client catalogClient = new CatalogClient().getClient();
                        boolean result = catalogClient.deleteBulkPricingForItemById(id);
                        return result;
                }
                catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not delete bulk pricing");
                        return false;
                }
        }
        
        public boolean deleteBulkPricingForItem(long itemId){
                try{
                Client catalogClient = new CatalogClient().getClient();
                boolean result = catalogClient.deleteBulkPricingForItem(itemId);
                return result;
                }
                catch (Exception e){
                        e.printStackTrace();
                        logger.info("Could not delete all bulk pricing");
                        return false;
                }
        }
        
        public List<CategoryHsnCode> getHsnCodesByCategoryId(int categoryId) {
                List<CategoryHsnCode> categoryHsnCodes = new ArrayList<CategoryHsnCode>();
                try{
                        Client client2 = new CatalogClient().getClient();
                        for(in.shop2020.model.v1.catalog.CategoryHsnCode e : client2.getHsnCodesByCategory(categoryId)){
                                CategoryHsnCode categoryHsnCode = new CategoryHsnCode();
                                categoryHsnCode.setCategoryId(Long.valueOf(e.getCategoryId()).intValue());
                                categoryHsnCode.setHsnCode(e.getHsnCode());
                                categoryHsnCode.setDescription(e.getDescription());
                                categoryHsnCodes.add(categoryHsnCode);
                        }
                }catch(Exception e){
                        e.printStackTrace();
                        logger.info("Could not get Hsn Codes By Category Id");
                }
                return categoryHsnCodes;
        }
        
}