/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Passbook;

/**
 *
 * @author IPKS
 */
import DataEntryBean.PassbookBean;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;

public class PassbookPrinter implements Printable {

    private String accNo;
    private static ArrayList<String> arr = new ArrayList<String>();
    private static double width = 7.5d * 72d;
    private static double height = 7.3d * 72d;
    private static double margin = 5d;
    private static double header = 10;
    private static double date_width = 30;
    private static double nara_width = 250;
    private static double cheque_width = 60;
    private static double withdraw_width = 50;
    private static double deposit_width = 50;
    private static double no_of_lines = 17;
    private static double gap = 3;
    public boolean successFlag = false;

    public PassbookPrinter(ArrayList<PassbookBean> alPassbookBean) {
        // TODO Auto-generated constructor stub
        //accNo = arg0;

        //InputStream inputStream = null;

        try {
            Properties prop = new Properties();
            String propFileName = "config.properties";
            String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
            absolute = absolute.substring(absolute.indexOf("/") + 1, absolute.lastIndexOf("/") + 1);
            System.out.println(absolute);
            absolute = absolute.replace('\\', '/');
            absolute = absolute.concat(propFileName);


            prop.load(new FileInputStream(absolute));

            System.out.println(absolute);
            //throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            System.out.println("width: " + width);


            width = Double.parseDouble(prop.getProperty("WIDTH"));
            height = Double.parseDouble(prop.getProperty("HEIGHT"));
            margin = Double.parseDouble(prop.getProperty("MARGIN"));
            header = Double.parseDouble(prop.getProperty("HEADER"));
            date_width = Double.parseDouble(prop.getProperty("DATE_WIDTH"));
            nara_width = Double.parseDouble(prop.getProperty("NARA_WIDTH"));
            cheque_width = Double.parseDouble(prop.getProperty("CHEQUE_WIDTH"));
            withdraw_width = Double.parseDouble(prop.getProperty("WITHDRAW_WIDTH"));
            deposit_width = Double.parseDouble(prop.getProperty("DEPOSIT_WIDTH"));
            no_of_lines = Double.parseDouble(prop.getProperty("NO_OF_LINES"));
            gap = Double.parseDouble(prop.getProperty("GAP"));

            System.out.println("width: " + width);
            //inputStream.close();

        } catch (Exception e) {
           // System.out.println("Exception: " + e);
            System.out.println("width: " + width);
        
        } finally {
            System.out.println("Processing done.");
        }


        double bal = 17563.89;
        DecimalFormat df2 = new DecimalFormat(".##");
        int i;

        PassbookBean oPassbookBean = null;

        for (i = 0; i < alPassbookBean.size(); i++) {

            oPassbookBean = alPassbookBean.get(i);
            /*String seq = "" + Calendar.getInstance().getTimeInMillis();
            int l = seq.length();
            int a = Integer.parseInt(seq.substring(l - 3, l));
            double e = 3.4;
            double d = a * i * e;

            bal = bal + d;
            arr.add("05-07-17,NARRATION TEXT " + i + ",,," + df2.format(d) + "," + df2.format(bal));*/
            String addToPrinter;
            addToPrinter = blankNull(oPassbookBean.getTxn_date());
            addToPrinter = addToPrinter + "," + blankNull(oPassbookBean.getNarration());

            if (!(oPassbookBean.getDr_amt() == null || oPassbookBean.getCr_amt() == null)) {
                if (!oPassbookBean.getDr_amt().equalsIgnoreCase("0")) {
                    addToPrinter = addToPrinter + "," + blankNull(oPassbookBean.getDr_amt());
                } else {
                    addToPrinter = addToPrinter + ",,";
                }

                if (!oPassbookBean.getCr_amt().equalsIgnoreCase("0")) {
                    addToPrinter = addToPrinter + "," + blankNull(oPassbookBean.getCr_amt());
                } else {
                    addToPrinter = addToPrinter + ",,";
                }
            } else {
                addToPrinter = addToPrinter + ",,";
            }
            addToPrinter = addToPrinter + "," + blankNull(oPassbookBean.getEnd_bal());
            this.arr.add(addToPrinter);
            System.out.println(this.getClass());
            //System.out.println(this.);

        }

        System.out.println("ArrayList size:  " + this.arr.size());

        PrinterJob job = PrinterJob.getPrinterJob();

        PageFormat pf = job.defaultPage();
        Paper paper = pf.getPaper();

        paper.setSize(width, height);

        paper.setImageableArea(
                margin,
                margin + header,
                width - (margin * 2),
                height - (margin * 2));


        System.out.println("Before- " + dump(paper));
        pf.setOrientation(PageFormat.PORTRAIT);
        pf.setPaper(paper);
        System.out.println("After- " + dump(paper));
        System.out.println("After- " + dump(pf));
        //dump(pf);
        PageFormat validatePage = job.validatePage(pf);
        System.out.println("Valid- " + dump(validatePage));

        Book pBook = new Book();
        pBook.append(new PassbookPrinter(), pf);

        job.setPageable(pBook);

        //job.setPrintable(this);
        boolean ok = job.printDialog();
        if (ok) {
            try {
                job.print();
                successFlag = true;
                arr.clear();
            } catch (PrinterException e) {
                // TODO Auto-generated catch block
               // e.printStackTrace();
               System.out.println("Error occurred during processing.");
            }
        }
    }

    public PassbookPrinter() {
        // TODO Auto-generated constructor stub
    }

    public String blankNull(String s) {
        return (s == null) ? "" : s;
    }

    protected static String dump(Paper paper) {
        StringBuilder sb = new StringBuilder(64);
        sb.append(paper.getWidth()).append("x").append(paper.getHeight()).append("/").append(paper.getImageableX()).append("x").
                append(paper.getImageableY()).append(" - ").append(paper.getImageableWidth()).append("x").append(paper.getImageableHeight());
        return sb.toString();
    }

    protected static String dump(PageFormat pf) {
        Paper paper = pf.getPaper();
        return dump(paper);
    }

    @Override
    public int print(Graphics g, PageFormat pf, int page)
            throws PrinterException {
        // TODO Auto-generated method stub
        System.out.println("print");

        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());


        g2d.setFont(new Font("TIMES NEW ROMAN", Font.PLAIN, 7));

        System.out.println("ArrayList size:  " + this.arr.size());

        //int buff= 10;
        double y = pf.getImageableY();
        for (int i = 1; i <= arr.size(); i++) {
            //System.out.println(arr.get(i-1));
            //g2d.drawString(arr.get(i-1), 2, buff*i);

            double x = pf.getImageableX();


            if (i != 1) {
                if (i == no_of_lines) {
                    y = (gap * 10) + (y + 10);
                } else {
                    y = y + 10;
                }
            }


            String[] tokens = arr.get(i - 1).split(",");

            for (int j = 0; j < tokens.length; j++) {

                switch (j) {

                    case 1:
                        //Narration
                        x = x + date_width;
                        break;
                    case 2:
                        //Cheque
                        x = x + nara_width;
                        break;
                    case 3:
                        //Withdraw
                        x = x + cheque_width;
                        break;
                    case 4:
                        //Deposit
                        x = x + withdraw_width;
                        break;

                    case 5:
                        //Bal
                        x = x + deposit_width;
                        break;
                }

                g2d.drawString(tokens[j], (int) x, (int) y);

            }


            System.out.println(i);
        }

        //tell the caller that this page is part of the printed document
        return PAGE_EXISTS;

    }
}

