Subversion Repositories SmartDukaan

Rev

Rev 18457 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.catalog.dashboard.client;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

import in.shop2020.catalog.dashboard.server.CatalogServiceImpl;
import in.shop2020.catalog.dashboard.shared.CategoryHsnCode;
import in.shop2020.catalog.dashboard.shared.Item;
import in.shop2020.catalog.dashboard.shared.Utils;
import in.shop2020.catalog.dashboard.shared.VendorItemMapping;
import in.shop2020.catalog.dashboard.shared.VendorPricings;

/**
 * ItemForm is a DialogBox which is created on the click of Add Item button in ItemActions.
 * This contains UI fields to fill up item attributes. It also contains tables for adding
 * vendor prices and vendor mapping keys.
 *
 */
public class ItemForm extends DialogBox implements ComingSoon{

        interface ItemFormUiBinder extends UiBinder<Widget, ItemForm> {}
        private static ItemFormUiBinder uiBinder = GWT.create(ItemFormUiBinder.class);
        
        private final static CatalogServiceAsync catalogService = GWT.create(CatalogService.class);
        private final int TABLE_INDEX_VENDORID = 0,
        TABLE_INDEX_VENDOR_DESC = 1, 
        TABLE_INDEX_ITEM_KEY = 2,
        TABLE_INDEX_MOP = 2,
        TABLE_INDEX_DP = 3,
        TABLE_INDEX_TP = 4,
        TABLE_INDEX_NLC = 5;

        private static boolean entityIdMandatory = Utils.isEntityIdMandatory();

        @UiField TextBox productGroup, catalogItemId,existingItemId;
        @UiField TextBox brand, modelNumber, modelName, color, comments,holdInventory,defaultInventory;
        @UiField TextBox mrp, sellingPrice, weight, bestDealText, bestDealValue, bestSellingRank,bestDealsDetailsText,bestDealsDetailsLink, minStockLevel, numOfDaysStock, freebieItemId,asin,packQuantity;
        @UiField DateBox startDate, retireDate, comingSoonStartDate, expectedArrivalDate;
        @UiField Button addButton, cancelButton, comingSoonButton,searchButton;
        @UiField CheckBox defaultForEntity, risky, itemType, hasItemNo, clearance, showSellingPrice;
        @UiField FlexTable headerVendor, vendorTable;
        @UiField FlexTable headerVendorM, vendorTableM;
        @UiField ListBox preferredVendor,preferredInsurer, categories, hsnCode;

        public ItemForm(){
                setText("Add New Item");
                setWidget(uiBinder.createAndBindUi(this));
                initVendorKeysHeader();
                initVendorPricesHeader();
                preferredVendor.addItem("select");
                for(Entry<Long, String> e : Utils.getAllVendors().entrySet()){
                        preferredVendor.addItem(e.getValue());
                }
                if(!entityIdMandatory) {
                        catalogItemId.setEnabled(false);
                }
                preferredInsurer.addItem("select", "0");
                for(Entry<Long, String> e : Utils.getAllInsurers().entrySet()){
                        preferredInsurer.addItem(e.getValue(),e.getKey().toString());
                }
                
                categories.addItem("select", "0");
                for(Entry<Long, String> e : Utils.getAllCategoriesMap().entrySet()){
                        categories.addItem(e.getValue(),e.getKey().toString());
                }
                
                //System.out.println("\n\n\nInitial ui ..... \n\n\n");
                //hsnCode.addItem("select");
                categories.addChangeHandler(new ChangeHandler() {
                public void onChange(ChangeEvent arg0) {
                        hsnCode.clear();
                        int categoryId = Integer.parseInt(categories.getValue(categories.getSelectedIndex()));
                        System.out.println("fired onChangeEvent categoryId : "+categoryId);
                        catalogService.getHsnCodesByCategoryId(categoryId, new AsyncCallback<List<CategoryHsnCode>>() {
                                
                                        public void onFailure(Throwable arg0) {
                                                arg0.printStackTrace();
                                        }

                                        public void onSuccess(List<CategoryHsnCode> arg0) {
                                                for(CategoryHsnCode categoryHsnCode : arg0){
                                                hsnCode.addItem(categoryHsnCode.getDescription() + " ("+ categoryHsnCode.getHsnCode() + ")", categoryHsnCode.getHsnCode());
                                        }
                                        }
                                
                                });
                        
                }
                        
                });

        }

        /**
         * initialises vendor item key table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a new vendor item key. 
         */
        private void initVendorKeysHeader(){
                headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "400px");
                headerVendorM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY + 1, "50px");

                headerVendorM.setText(0, TABLE_INDEX_VENDORID, "Vendor Id");
                headerVendorM.setText(0, TABLE_INDEX_VENDOR_DESC, "Vendor");
                headerVendorM.setText(0, TABLE_INDEX_ITEM_KEY, "Item Key");

                headerVendorM.getCellFormatter().setVisible(0, TABLE_INDEX_VENDORID, false);

                Button addButton = new Button("Add");
                headerVendorM.setWidget(0, TABLE_INDEX_ITEM_KEY + 1, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                VendorMappingDialog vendorMappingDialog = new VendorMappingDialog(productGroup.getText().trim(), brand.getText().trim(), 
                                                modelNumber.getText().trim(), color.getText().trim());
                                vendorMappingDialog.updateButton.setText("Add");
                                vendorMappingDialog.setVendorMappingUpdateListener(new VendorMappingDialog.VendorMappingUpdateListener() {
                                        @Override
                                        public boolean onUpdate(String key, long vendorId) {
                                                final int row = vendorTableM.getRowCount();
                                                vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                                                vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                                                vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY, "400px");
                                                vendorTableM.getColumnFormatter().setWidth(TABLE_INDEX_ITEM_KEY + 1, "50px");

                                                vendorTableM.setText(row, TABLE_INDEX_VENDORID, vendorId + "");
                                                vendorTableM.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                                                vendorTableM.setText(row, TABLE_INDEX_ITEM_KEY, key);
                                                Button removeButton = new Button("X");
                                                vendorTableM.setWidget(row, TABLE_INDEX_ITEM_KEY + 1, removeButton);

                                                vendorTableM.getCellFormatter().setVisible(row, TABLE_INDEX_VENDORID, false);
                                                removeButton.addClickHandler(new ClickHandler() {
                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                                vendorTableM.removeRow(row);
                                                        }
                                                });
                                                return true;
                                        }
                                });
                                vendorMappingDialog.show();
                        }
                });
        }

        /**
         * initialises vendor prices table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a prices for a new vendor 
         */
        private void initVendorPricesHeader(){
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_NLC, "128px");
                headerVendor.getColumnFormatter().setWidth(TABLE_INDEX_NLC + 1, "50px");

                headerVendor.setText(0, TABLE_INDEX_VENDORID, "Vendor Id");
                headerVendor.setText(0, TABLE_INDEX_VENDOR_DESC, "Vendor");
                headerVendor.setText(0, TABLE_INDEX_MOP, "MOP");
                headerVendor.setText(0, TABLE_INDEX_DP, "Dealer Price");
                headerVendor.setText(0, TABLE_INDEX_TP, "Transfer Price");
                headerVendor.setText(0, TABLE_INDEX_NLC, "NLC");

                headerVendor.getCellFormatter().setVisible(0, TABLE_INDEX_VENDORID, false);

                Button addButton = new Button("Add");
                headerVendor.setWidget(0, TABLE_INDEX_NLC + 1, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                VendorPricesDialog vendorPricesDialog = new VendorPricesDialog();
                                vendorPricesDialog.updateButton.setText("Add");
                                vendorPricesDialog.setVendorPriceUpdateListener(new VendorPricesDialog.VendorPriceUpdateListener() {
                                        @Override
                                        public boolean onUpdate(double mop, double dp, double tp, double nlc, long vendorId) {
                                                if(!vendorExists(vendorId)) {
                                                        Window.alert("Vendor already exists");
                                                        return false;
                                                }
                                                /*if(!validateVendorPrices(mop, dp, tp)) {
                            return false;
                        }*/
                                                final int row = vendorTable.getRowCount();
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC, "128px");
                                                vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC + 1, "50px");

                                                vendorTable.setText(row, TABLE_INDEX_VENDORID, vendorId + "");
                                                vendorTable.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                                                vendorTable.setText(row, TABLE_INDEX_MOP, mop + "");
                                                vendorTable.setText(row, TABLE_INDEX_DP, dp + "");
                                                vendorTable.setText(row, TABLE_INDEX_TP, tp + "");
                                                vendorTable.setText(row, TABLE_INDEX_NLC, nlc + "");

                                                vendorTable.getCellFormatter().setVisible(row, TABLE_INDEX_VENDORID, false);

                                                Button removeButton = new Button("X");
                                                vendorTable.setWidget(row, TABLE_INDEX_NLC + 1, removeButton);
                                                removeButton.addClickHandler(new ClickHandler() {
                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                                vendorTable.removeRow(row);
                                                        }
                                                });
                                                return true;
                                        }
                                });
                                vendorPricesDialog.show();
                        }
                });
        }
        @UiHandler("searchButton")
        /**
         * On search button click the item id is searched if it exists then the attributes of the item id are filled into the item form.
         * Else an alert is displayed showing item id does not exists.
         */
        void searchItem(ClickEvent event){
                hsnCode.clear();
                preferredVendor.clear();
                preferredInsurer.clear(); 
                categories.clear();
                catalogItemId.setText(null);
                productGroup.setText(null);
                brand.setText(null);
                modelNumber.setText(null);
                modelName.setText(null);
                comments.setText(null);
                mrp.setText(null);
                sellingPrice.setText(null);
                weight.setText(null);
                hasItemNo.setValue(null);
                itemType.setValue(null);
                showSellingPrice.setValue(null);
                startDate.setValue(null);
                this.comingSoonStartDate.setValue(null);
                this.expectedArrivalDate.setValue(null);
                bestDealText.setText(null);
                bestDealsDetailsText.setText(null);
                bestDealsDetailsLink.setText(null);
                bestDealValue.setText(null);
                showSellingPrice.setValue(null);
                bestSellingRank.setText(null);
                minStockLevel.setText(null);
                numOfDaysStock.setText(null);
                defaultForEntity.setValue(null);
                freebieItemId.setText(null);
                asin.setText(null);
                holdInventory.setText(null);
                defaultInventory.setText(null);
                color.setText(null);
                vendorTable.removeAllRows();
                packQuantity.setText(null);
                if(!existingItemId.getText().trim().isEmpty()){
                        long id = Long.parseLong(existingItemId.getText().trim());

                        if(id <= 0) {
                                throw new NumberFormatException("Invalid value of Item Id");
                        }
                        else{
                                catalogService.getItem(id, new AsyncCallback<Item>() {
                                        @Override
                                        public void onFailure(Throwable caught) {
                                                Window.alert("Unable to fetch item details.");
                                        }
                                        @Override
                                        public void onSuccess(Item result) {
                                                if(result !=null){
                                                        fillItemForm(result);
                                                }
                                                else{
                                                        Window.alert("Invalid Item Id not found");
                                                }
                                        }
                                });

                        }
                }
                else{
                        Window.alert("Please enter item id");
                        GWT.log("Please enter an item id ");
                }
        }


        /**
         * This method is called if the valid item is returned and it populates the item entries in Item Form.
         * 
         */
        public void fillItemForm(Item item){
                int index = 0;
                preferredVendor.addItem("select");
        if (item.getPreferredVendor() == null) {
                preferredVendor.setSelectedIndex(index);
        }
        
        if((item.getVendorPricesMap() == null || item.getVendorPricesMap().isEmpty())) {
                if(item.getPreferredVendor() != null) {
                        index++;
                        preferredVendor.addItem(Utils.getVendorDesc(item.getPreferredVendor()));
                }
        }
        else {
                for(VendorPricings vendorDetail : item.getVendorPricesMap().values()){
                        index++;
                        preferredVendor.addItem(Utils.getVendorDesc(vendorDetail.getVendorId()));
                        if(item.getPreferredVendor() != null && item.getPreferredVendor() == vendorDetail.getVendorId()) {
                                preferredVendor.setSelectedIndex(index);
                        }
                }
                
                if(item.getPreferredVendor() != null && !item.getVendorPricesMap().containsKey(item.getPreferredVendor())){
                        index++;
                preferredVendor.addItem(Utils.getVendorDesc(item.getPreferredVendor()));
                preferredVendor.setSelectedIndex(index);
                }
        }
        index=0;
        preferredInsurer.addItem("select","0");
        preferredInsurer.setSelectedIndex(0);
        for (Map.Entry<Long, String> entry : Utils.getAllInsurers().entrySet()){
                index++;
                preferredInsurer.addItem(entry.getValue(),entry.getKey().toString());
                if(item.getPreferredInsurer()==entry.getKey()){
                        preferredInsurer.setSelectedIndex(index);  
                }
        }
        index = 0;
        categories.addItem("select", "0");
        categories.setSelectedIndex(0);
        for(Map.Entry<Long, String> entry : Utils.getAllCategoriesMap().entrySet()){
                index ++;
                categories.addItem(entry.getValue(), entry.getKey().toString());
                if(item.getCategoryItemId() == entry.getKey()){
                        categories.setSelectedIndex(index);
                }
        }
        
        
                catalogItemId.setText(Long.toString(item.getCatalogItemId()));
                productGroup.setText(item.getProductGroup());
                brand.setText(item.getBrand());
                modelNumber.setText(item.getModelNumber());
                modelName.setText(item.getModelName());
                comments.setText(item.getComments());
                mrp.setText(item.getMrp() != null ? item.getMrp()+"" : "");
                packQuantity.setText(item.getPackQuantity().toString());
                sellingPrice.setText(item.getSellingPrice() != null ? item.getSellingPrice()+"" : "");
                weight.setText(item.getWeight() != null ? item.getWeight()+"" : "");
                hasItemNo.setValue(item.isHasItemNo());
                itemType.setValue(item.isItemType());
                showSellingPrice.setValue(item.isShowSellingPrice());
                startDate.setValue(new Date(item.getStartDate()));
                if(item.getComingSoonStartDate() != null){
                        this.comingSoonStartDate.setValue(new Date(item.getComingSoonStartDate()));
                }else {
                        this.comingSoonStartDate.setValue(null);
                }
                if(item.getExpectedArrivalDate() != null){
                        this.expectedArrivalDate.setValue(new Date(item.getExpectedArrivalDate()));
                }else {
                        this.expectedArrivalDate.setValue(null);
                }
                bestDealText.setText(item.getBestDealsText());
                bestDealsDetailsText.setText(item.getBestDealsDetailsText());
                bestDealsDetailsLink.setText(item.getBestDealsDetailsLink());
                bestDealValue.setText(item.getBestDealsValue() != null ? item.getBestDealsValue()+"" : "");
                showSellingPrice.setValue(item.isShowSellingPrice());
                bestSellingRank.setText(item.getBestSellingRank() != null ? item.getBestSellingRank()+"" : "");
                minStockLevel.setText(item.getMinStockLevel() != null ? item.getMinStockLevel()+"" : "");
                numOfDaysStock.setText(item.getNumOfDaysStock() != null ? item.getNumOfDaysStock()+"" : "");
                defaultForEntity.setValue(item.isDefaultForEntity());
                freebieItemId.setText(item.getFreebieItemId().toString());
                holdInventory.setText(Long.toString(item.getHoldInventory()));
                defaultInventory.setText(Long.toString(item.getDefaultInventory()));
                Map<Long, VendorPricings> map = item.getVendorPricesMap();
                for (Map.Entry<Long, VendorPricings> vendorItem : map.entrySet()) {
                        final int row = vendorTable.getRowCount();
                        long vendorId = vendorItem.getKey();
                        double mop = vendorItem.getValue().getMop();
                        double dp  = vendorItem.getValue().getDealerPrice();
                        double tp =  vendorItem.getValue().getTransferPrice();
                        double nlc = vendorItem.getValue().getNlc();
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDORID, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_VENDOR_DESC, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_MOP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_DP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_TP, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC, "128px");
                        vendorTable.getColumnFormatter().setWidth(TABLE_INDEX_NLC + 1, "50px");
                        vendorTable.setText(row, TABLE_INDEX_VENDORID, vendorId + "");
                        vendorTable.setText(row, TABLE_INDEX_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                        vendorTable.setText(row, TABLE_INDEX_MOP, mop + "");
                        vendorTable.setText(row, TABLE_INDEX_DP, dp + "");
                        vendorTable.setText(row, TABLE_INDEX_TP, tp + "");
                        vendorTable.setText(row, TABLE_INDEX_NLC, nlc + "");
                        vendorTable.getCellFormatter().setVisible(row, TABLE_INDEX_VENDORID, false);
                        Button removeButton = new Button("X");
                        vendorTable.setWidget(row, TABLE_INDEX_NLC + 1, removeButton);
                        removeButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        vendorTable.removeRow(row);
                                }
                        });
                }
        }


        @UiHandler("addButton")
        /**
         * On add button click a new Item instance is created and all the information from UI fields is dumped in this item instance.
         * This item instance is then passed to the service to be added to the database.
         */
        void addItem(ClickEvent event) {
                if(entityIdMandatory) {
                        long entityId = 0;
                        try {
                                if(!catalogItemId.getText().trim().isEmpty()) {
                                        entityId = Long.parseLong(catalogItemId.getText().trim());
                                        if(entityId <= 0) {
                                                throw new NumberFormatException("Invalid value of Catalog Item Id");
                                        }
                                }
                                else {
                                        Window.alert("Catalog Item Id can not be empty");
                                        return;
                                }
                        } catch(NumberFormatException ex) {
                                Window.alert("Invalid value of Catalog Item Id");
                                return;
                        }
                        catalogService.checkEntityId(entityId, new AsyncCallback<Boolean>() {
                                @Override
                                public void onFailure(Throwable caught) {
                                        GWT.log("Error checking Catalog Item Id");
                                        Window.alert("Error checking Catalog Item Id");
                                        return;
                                }
                                @Override
                                public void onSuccess(Boolean result) {
                                        if(!result) {
                                                Window.alert("Invalid value of Catalog Item Id");
                                                return;
                                        }
                                        addNewItem();
                                }
                        });
                }
                else {
                        catalogService.checkSimilarItem(brand.getText().trim(), modelNumber.getText().trim(),
                                        modelName.getText().trim(), color.getText().trim(), new AsyncCallback<Long>() {
                                @Override
                                public void onFailure(Throwable caught) {
                                        GWT.log("Error checking similar item");
                                        Window.alert("Error checking similar item");
                                        return;
                                }
                                @Override
                                public void onSuccess(Long result) {
                                        if(result != 0) {
                                                Window.alert("Similar product exists with Item Id " + result);
                                                return;
                                        }
                                        addNewItem();
                                }
                        });
                }
        }

        private void addNewItem() {
                Item item = new Item();
                if(!productGroup.getText().trim().isEmpty()) {
                        item.setProductGroup(productGroup.getText().trim());
                }
                else {
                        Window.alert("Product Group can not be empty.");
                        return;
                }

                if(entityIdMandatory) {
                        try {
                                if(!catalogItemId.getText().trim().isEmpty()) {
                                        long entityId = Long.parseLong(catalogItemId.getText().trim());
                                        if(entityId <= 0) {
                                                throw new NumberFormatException("Invalid value of Catalog Item Id");
                                        }
                                        item.setCatalogItemId(entityId);
                                }
                                else {
                                        Window.alert("Catalog Item Id can not be empty");
                                        return;
                                }
                        } catch(NumberFormatException ex) {
                                Window.alert("Invalid value of Catalog Item Id");
                                return;
                        }
                }
                item.setBrand(brand.getText().trim());
                item.setModelNumber(modelNumber.getText().trim());
                item.setModelName(modelName.getText().trim());
                item.setColor(color.getText().trim());
                item.setComments(comments.getText().trim());
                try {
                        if(!mrp.getText().trim().isEmpty()) {
                                double mrpValue = Double.parseDouble(mrp.getText().trim());
                                if(mrpValue <= 0) {
                                        throw new NumberFormatException("Negative value of MRP");
                                }
                                item.setMrp(mrpValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid MRP format/value. Value shoule be greater than zero");
                        return;
                }
                try {
                        if(!sellingPrice.getText().trim().isEmpty()) {
                                double spValue = Double.parseDouble(sellingPrice.getText().trim());
                                if(spValue <= 0) {
                                        throw new NumberFormatException("Negative value of Selling price");
                                }
                                item.setSellingPrice(spValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Selling Price format/value. Value shoule be greater than zero");
                        return;
                }
                try {
                        if(!weight.getText().trim().isEmpty()) {
                                double wtValue = Double.parseDouble(weight.getText().trim());
                                if(wtValue <= 0) {
                                        throw new NumberFormatException("Negative value of Weight");
                                }
                                item.setWeight(wtValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid weight format/value. Value shoule be greater than zero");
                        return;
                }
                try {
                        if(!packQuantity.getText().trim().isEmpty()) {
                                long packQuantityValue = Long.parseLong(packQuantity.getText().trim());
                                if(packQuantityValue < 1) {
                                        throw new NumberFormatException("Illegal value of PackQuantity");
                                }
                                item.setPackQuantity(packQuantityValue);
                        }
                        else{
                                Window.alert("Invalid PackQuantity format/value. Value should can't be empty");
                                return;
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid PackQuantity format/value. Value should be greater than zero");
                        return;
                }
                try {
                        if(!startDate.getTextBox().getText().trim().equals("")) {
                                item.setStartDate(startDate.getValue().getTime());
                        }
                } catch(Exception ex) {
                        Window.alert("Invalid start date format");
                        return;
                }
                if(comingSoonStartDate.getValue()==null){
                        item.setComingSoonStartDate(null);
                }else {
                        item.setComingSoonStartDate(comingSoonStartDate.getValue().getTime());
                }
                if(expectedArrivalDate.getValue()==null){
                        item.setExpectedArrivalDate(null);
                }else {
                        item.setExpectedArrivalDate(expectedArrivalDate.getValue().getTime());
                }
                item.setBestDealsText(bestDealText.getText().trim());
                item.setBestDealsDetailsText(bestDealsDetailsText.getText().trim());
                item.setBestDealsDetailsLink(bestDealsDetailsLink.getText().trim());
                try {
                        if(!bestDealValue.getText().trim().equals("")) {
                                double bdValue = Double.parseDouble(bestDealValue.getText().trim());
                                if(bdValue < 0) {
                                        throw new NumberFormatException("Negative value of BestDealValue");
                                }
                                item.setBestDealsValue(bdValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid best deal value format");
                        return;
                }
                try {
                        if(!bestSellingRank.getText().trim().equals("")) {
                                long bsrValue = Long.parseLong(bestSellingRank.getText().trim());
                                if(bsrValue < 0) {
                                        throw new NumberFormatException("Negative value of Best Selling Rank");
                                }
                                item.setBestSellingRank(bsrValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid best selling rank format");
                        return;
                }

                try {
                        if(!minStockLevel.getText().trim().equals("")) {
                                long msl = Long.parseLong(minStockLevel.getText().trim());
                                if(msl < 0) {
                                        throw new NumberFormatException("Negative value of Min Stock Value");
                                }
                                item.setMinStockLevel(msl);
                        }else {
                                item.setMinStockLevel(0L);
                        }
                } catch(NumberFormatException ex) {
                        item.setMinStockLevel(0L);
                        Window.alert("Invalid min Stock Level. Setting it to zero(0)");
                        return;
                }

                try {
                        if(!numOfDaysStock.getText().trim().equals("")) {
                                Long nds = Long.parseLong(numOfDaysStock.getText().trim());
                                if(nds < 0) {
                                        throw new NumberFormatException("Negative value of Num of Days Of Stock");
                                }
                                item.setNumOfDaysStock(nds.intValue());
                        } else {
                                item.setNumOfDaysStock(0);
                        }
                } catch(NumberFormatException ex) {
                        item.setNumOfDaysStock(0);
                        Window.alert("Invalid min Stock Level. Setting it to zero(0)");
                        return;
                }

                try {
                        if(!freebieItemId.getText().trim().equals("")) {
                                long freeItemId = Long.parseLong(freebieItemId.getText().trim());
                                if(freeItemId < 0) {
                                        throw new NumberFormatException("Negative value of freebieItemId ");
                                }
                                item.setFreebieItemId(new Long(freeItemId));
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid freebie ItemId");
                        return;
                }
                item.setAsin(asin.getText().trim());

                try {
                        if(!holdInventory.getText().trim().equals("")) {
                                long hold_inventory = Long.parseLong(holdInventory.getText().trim());
                                if(hold_inventory < 0) {
                                        throw new NumberFormatException("Negative value of Hold Inventory");
                                }
                                item.setHoldInventory(hold_inventory);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Hold Inventory Value");
                        return;
                }

                try {
                        if(!defaultInventory.getText().trim().equals("")) {
                                long default_inventory = Long.parseLong(defaultInventory.getText().trim());
                                if(default_inventory < 0) {
                                        throw new NumberFormatException("Negative value of Default Inventory");
                                }
                                item.setDefaultInventory(default_inventory);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Default Inventory Value");
                        return;
                }
                item.setDefaultForEntity(defaultForEntity.getValue());
                item.setRisky(risky.getValue());
                item.setHasItemNo(hasItemNo.getValue());
                item.setItemType(itemType.getValue());
                if(preferredVendor.getSelectedIndex() == 0) {
                        Window.alert("Invalid Vendor Selected");
                        return;
                }
                else {
                        item.setPreferredVendor(Utils.getVendorId(preferredVendor.getItemText(preferredVendor.getSelectedIndex())));
                }
                item.setPreferredInsurer(Long.parseLong(preferredInsurer.getValue(preferredInsurer.getSelectedIndex())));
                //item.setCategoryItemId(Integer.parseInt(categories.getValue(categories.getSelectedIndex())));
                item.setHsnCode(hsnCode.getValue(hsnCode.getSelectedIndex()));
                /*Create an instance of VendorPricings for each row in vendor pricing table. Set the vendor prices to the instance.
          Add the instance to map and set the map to the item instance created above.*/
                Map<Long, VendorPricings> vendorPrices = new HashMap<Long, VendorPricings>();
                VendorPricings v;
                for(int row = 0; row < vendorTable.getRowCount(); row++) {
                        v = new VendorPricings();
                        v.setMop(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_MOP)));
                        v.setDealerPrice(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_DP)));
                        v.setTransferPrice(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_TP)));
                        v.setVendorId(Long.parseLong(vendorTable.getText(row, TABLE_INDEX_VENDORID)));
                        v.setNlc(Double.parseDouble(vendorTable.getText(row, TABLE_INDEX_NLC)));
                        vendorPrices.put(v.getVendorId(), v);
                }
                item.setVendorPricesMap(vendorPrices);

                /*Create an instance of VendorKeys for each row in vendor pricing table. Set the vendor prices to the instance.
        Add the instance to map and set the map to the item instance created above.*/
                Map<String, VendorItemMapping> vendorMappings = new HashMap<String, VendorItemMapping>();
                VendorItemMapping vMapping;
                for(int row = 0; row < vendorTableM.getRowCount(); row++) {
                        vMapping = new VendorItemMapping();
                        vMapping.setItemKey(vendorTableM.getText(row, TABLE_INDEX_ITEM_KEY));
                        vMapping.setVendorId(Long.parseLong(vendorTableM.getText(row, TABLE_INDEX_VENDORID)));
                        vendorMappings.put(vMapping.getVendorId() + Item.KEY_SEPARATOR + vMapping.getItemKey(), vMapping);
                }
                item.setVendorKeysMap(vendorMappings);
                if(!Utils.validateItem(item)) {
                        return;
                }

                /*Service method to add item. */
                catalogService.addItem(item, new AsyncCallback<Long>() {
                        @Override
                        public void onSuccess(Long result) {
                                if(result == null || result == 0) {
                                        Window.alert("Error while adding item");
                                        return;
                                }
                                Window.alert("Item added successfully. Id = " + result);
                                hide();
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Error while adding item");
                        }
                });
        }

        @UiHandler("cancelButton")
        void closeForm(ClickEvent event) {
                this.hide();
        }

        /**
         * Checks if vendor details already exists corresponding to the vendor Id parameter. 
         */
        private boolean vendorExists(long vendorId) {
                long id;
                for(int i = 0; i < vendorTable.getRowCount(); i++) {
                        id = Long.parseLong(vendorTable.getText(i, TABLE_INDEX_VENDORID));
                        if(vendorId == id) {
                                return false;
                        }
                }
                return true;
        }

        /**
         * validate vendor prices (MOP, DealerPrice, TransferPrice)
         */
        @SuppressWarnings("unused")
        private boolean validateVendorPrices(double mop, double dp, double tp) {
                double mrpValue;
                try {
                        mrpValue = Double.parseDouble(mrp.getText().trim());
                } catch (NumberFormatException ex) {
                        Window.alert("Invalid MRP value.");
                        return false;
                }
                if(mrpValue < mop) {
                        Window.alert("MOP cannot be more than MRP.");
                        return false;
                }
//              if(tp > mop) {
//                      Window.alert("Transfer Price cannot be more than MOP.");
//                      return false;
//              }
                return true;
        }

        @UiHandler("comingSoonButton")
        void onComingSoonButtonClick(ClickEvent event) {
                ComingSoonDialog cd = new ComingSoonDialog(this);
                cd.show();
        }
        
        public void setComingSoonStartDate(Date date){
                this.comingSoonStartDate.setValue(date);
        }
        public void setBestDealsText(String bestDealsText){
                this.bestDealText.setText(bestDealsText);
        }

        public void setExpectedArrivalDate(Date date){
                this.expectedArrivalDate.setValue(date);
        }

        public void setShowPrice(boolean b){
                this.showSellingPrice.setValue(b);
        }

        public boolean isShowPrice(){
                return this.showSellingPrice.getValue();
        }

        @Override
        public String getBestDealsText() {
                return this.bestDealText.getValue();
        }

        @Override
        public Date getComingSoonStartDate() {
                return this.comingSoonStartDate.getValue();
        }

        @Override
        public Date getExpectedArrivalDate() {
                return this.expectedArrivalDate.getValue();
        }

        public TextBox getBestDealsDetailsText() {
                return bestDealsDetailsText;
        }

        public void setBestDealsDetailsText(TextBox bestDealsDetailsText) {
                this.bestDealsDetailsText = bestDealsDetailsText;
        }

        public TextBox getBestDealsDetailsLink() {
                return bestDealsDetailsLink;
        }

        public void setBestDealsDetailsLink(TextBox bestDealsDetailsLink) {
                this.bestDealsDetailsLink = bestDealsDetailsLink;
        }
}