package com.reallinkbilling.ajax;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.ProductBarcodeDetailsDAO;
import com.reallinkbilling.pojo.BarcodeProductCatalogItem;
import com.reallinkbilling.util.BarcodeProductDetailsSessionLoader;

/**
 * JSON for barcode-bill autocomplete. On each request, reloads the session map
 * from the database (same as "Reload Product List") so a corrupt or
 * incompatible session <code>barcodeProductDetails</code> can never leave the
 * client with an empty list while reload still fixes it.
 */
public class GetBarcodeProductCatalog extends ActionSupport implements SessionAware {

    private static final long serialVersionUID = 1L;
    private SessionMap<String, Object> sessionMap;

    private List<BarcodeProductCatalogItem> catalogItems = new ArrayList<BarcodeProductCatalogItem>();

    @SuppressWarnings("unchecked")
    public String execute() {
        if (getSessionMap() == null || getSessionMap().get("login") == null) {
            catalogItems = new ArrayList<BarcodeProductCatalogItem>();
            return SUCCESS;
        }
        try {
            /* Same DB path as Reload: always replace session map (avoids "works only after Reload"). */
            try {
                BarcodeProductDetailsSessionLoader.loadAndPutInSession(getSessionMap());
            } catch (SQLException e) {
            } catch (IOException e) {
            }
            Map<String, ProductBarcodeDetailsDAO> map = (Map<String, ProductBarcodeDetailsDAO>) getSessionMap()
                    .get("barcodeProductDetails");
            if (map == null || map.isEmpty()) {
                catalogItems = new ArrayList<BarcodeProductCatalogItem>();
                return SUCCESS;
            }
            for (ProductBarcodeDetailsDAO d : new ArrayList<>(map.values())) {
                if (d == null || d.getProductCode() == null) {
                    continue;
                }
                try {
                    BarcodeProductCatalogItem row = new BarcodeProductCatalogItem();
                    String alias = d.getProductAlias() != null ? d.getProductAlias() : "";
                    String nameE = d.getProductNameEn() != null ? d.getProductNameEn() : "";
                    String nameM = d.getProductNameMr() != null ? d.getProductNameMr() : "";
                    row.setProductId(d.getProductId() != null ? d.getProductId().trim() : "");
                    row.setProductCode(d.getProductCode().trim());
                    row.setLabel(nameE + " | " + nameM + " | " + alias);
                    row.setProductName(nameE);
                    row.setProductNameMr(nameM);
                    row.setProductAlias(alias);
                    row.setTaxId(String.valueOf(d.getTaxId()));
                    row.setSalesUnit(d.getSalesUnit());
                    row.setSalesRate(d.getBarcodeMRP());
                    row.setAmount(d.getBarcodeMRP());
                    row.setAmountAfterDiscount(d.getSalesPrice());
                    row.setQuantity(d.getBarCodeQuantity());
                    catalogItems.add(row);
                } catch (RuntimeException skipRow) {
                    /* One bad row must not clear the whole catalog. */
                }
            }
        } catch (Exception e) {
        }
        return SUCCESS;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.sessionMap = (SessionMap<String, Object>) map;
    }

    public SessionMap<String, Object> getSessionMap() {
        return sessionMap;
    }

    public List<BarcodeProductCatalogItem> getCatalogItems() {
        return catalogItems;
    }

    public void setCatalogItems(List<BarcodeProductCatalogItem> catalogItems) {
        this.catalogItems = catalogItems;
    }
}
