package com.reallinkbilling.print;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class WindowsDirectPrint extends ActionSupport implements SessionAware {

    private SessionMap<String,Object> sessionMap;  

    private String billNumber;
    private String billDateTime;
    private String customerName;
    private String customerMobile;
    private String printerName = "EPSON TM-T88V ReceiptE4"; // default installed name

    public String print() {
        HttpServletResponse resp = org.apache.struts2.ServletActionContext.getResponse();
        try {
            PrintService svc = findPrinter(printerName);
            if (svc == null) {
                write(resp, "<h3>Windows printer not found: "+escapeHtml(printerName)+"</h3>");
                return null;
            }

            String text = buildReceipt();

            DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;
            Doc doc = new SimpleDoc(text, flavor, null);
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            DocPrintJob job = svc.createPrintJob();
            job.print(doc, aset);

            write(resp, "<h3>Sent to Windows printer</h3><div>Printer: "+escapeHtml(svc.getName())+"</div>");
            return null;
        } catch (Exception e) {
            write(resp, "<h3>Windows print failed: "+escapeHtml(e.getMessage())+"</h3>");
            return null;
        }
    }

    private PrintService findPrinter(String name) {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        if (services != null) {
            for (PrintService s : services) {
                if (s.getName().equalsIgnoreCase(name) || s.getName().contains(name)) {
                    return s;
                }
            }
        }
        return PrintServiceLookup.lookupDefaultPrintService();
    }

    private String buildReceipt() {
        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 Windows driver\n");
        sb.append("-----------------------------------------------\n\n\n");
        return sb.toString();
    }

    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;");
    }

    private void write(HttpServletResponse resp, String html) {
        try {
            resp.setContentType("text/html; charset=UTF-8");
            resp.getWriter().write("<html><body>"+html+"<script>setTimeout(function(){window.close();},1500);</script></body></html>");
            resp.getWriter().flush();
        } catch (Exception ignore) {}
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.sessionMap = (SessionMap<String, Object>) map;
    }

    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 getPrinterName() { return printerName; }
    public void setPrinterName(String printerName) { this.printerName = printerName; }
}


