package com.reallinkbilling.print;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

import jpos.JposException;
import jpos.POSPrinter;
import jpos.POSPrinterConst;

@SuppressWarnings("serial")
public class JavaPosBillPrint extends ActionSupport implements SessionAware {

    private SessionMap<String,Object> sessionMap;  

    private String billNumber;
    private String billDateTime;
    private String customerName;
    private String customerMobile;
    private String logicalName = "POSPrinter"; // default JavaPOS logical name

    public String print() {
        HttpServletResponse resp = org.apache.struts2.ServletActionContext.getResponse();
        POSPrinter printer = new POSPrinter();
        try {
            printer.open(logicalName);
            printer.claim(10000);
            printer.setDeviceEnabled(true);

            StringBuilder sb = new StringBuilder();
            Map<String,String> shopDetails = null;
            try { shopDetails = (Map<String,String>) sessionMap.get("shop_details"); } catch (Exception e) {}
            if (shopDetails != null) {
                String name = shopDetails.get("shopnameenglish");
                String addr = shopDetails.get("shopaddresseng");
                if (name != null) sb.append(name).append("\n");
                if (addr != null) sb.append(addr).append("\n");
            }
            sb.append("-----------------------------------------------\n");
            sb.append("Inv: ").append(nullToEmpty(billNumber)).append("    Date: ").append(nullToEmpty(billDateTime)).append("\n");
            if (customerName != null || customerMobile != null) {
                sb.append("Cust: ").append(nullToEmpty(customerName));
                if (customerMobile != null) sb.append("  Mob: ").append(customerMobile);
                sb.append("\n");
            }
            sb.append("-----------------------------------------------\n");
            sb.append("Items printed via JavaPOS\n");
            sb.append("-----------------------------------------------\n\n\n");

            printer.printNormal(POSPrinterConst.PTR_S_RECEIPT, sb.toString());
            printer.cutPaper(90);

            resp.setContentType("text/html; charset=UTF-8");
            resp.getWriter().write("<html><body><h3>Printed successfully via JavaPOS</h3><script>setTimeout(function(){window.close();},1500);</script></body></html>");
            resp.getWriter().flush();
            return null; // no further result processing
        } catch (JposException e) {
            try {
                resp.setContentType("text/html; charset=UTF-8");
                resp.getWriter().write("<html><body><h3>JavaPOS print failed: "+ escapeHtml(e.getMessage()) +"</h3></body></html>");
                resp.getWriter().flush();
            } catch (Exception ignore) {}
            return null;
        }
        catch(Exception e)
        {
        	return ""+e.getMessage();
        }
        finally {
            try { if (printer.getDeviceEnabled()) printer.setDeviceEnabled(false); } catch (Exception ignore) {}
            try { if (printer.getClaimed()) printer.release(); } catch (Exception ignore) {}
            try { if (printer.getState() != jpos.JposConst.JPOS_S_CLOSED) printer.close(); } catch (Exception ignore) {}
        }
    }

    private static String nullToEmpty(String s){ return s==null?"":s; }
    private static String escapeHtml(String s){
        if (s == null) return "";
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.sessionMap = (SessionMap<String, Object>) map;
    }
    public SessionMap<String, Object> getSessionMap() { return sessionMap; }

    public String getBillNumber() { return billNumber; }
    public void setBillNumber(String billNumber) { this.billNumber = billNumber; }
    public String getBillDateTime() { return billDateTime; }
    public void setBillDateTime(String billDateTime) { this.billDateTime = billDateTime; }
    public String getCustomerName() { return customerName; }
    public void setCustomerName(String customerName) { this.customerName = customerName; }
    public String getCustomerMobile() { return customerMobile; }
    public void setCustomerMobile(String customerMobile) { this.customerMobile = customerMobile; }
    public String getLogicalName() { return logicalName; }
    public void setLogicalName(String logicalName) { this.logicalName = logicalName; }
}


