package com.reallinkbilling.download;


import static java.awt.Color.WHITE;
import static org.apache.pdfbox.pdmodel.font.PDType1Font.HELVETICA;
import static org.vandeseer.easytable.settings.HorizontalAlignment.CENTER;
import static org.vandeseer.easytable.settings.HorizontalAlignment.LEFT;
import static org.vandeseer.easytable.settings.HorizontalAlignment.RIGHT;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.vandeseer.easytable.TableDrawer;
import org.vandeseer.easytable.structure.Row;
import org.vandeseer.easytable.structure.Table;
import org.vandeseer.easytable.structure.Table.TableBuilder;
import org.vandeseer.easytable.structure.cell.TextCell;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;

public class DownloadAllSalesman extends ActionSupport implements SessionAware {

    private static final long serialVersionUID = 1L;

    private SessionMap<String, Object> sessionMap;

    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;

    private static final float PADDING5 = 5f;
    private static final float PADDING20 = 20f;
    private static final float PADDING30 = 30f;

    /**
     * This is called if Struts action uses the default execute() method.
     */
    @Override
    public String execute() {

        download();

        return NONE;
    }

    /**
     * Download Salesman List PDF
     */
    public void download() {

        this.request = ServletActionContext.getRequest();
        this.response = ServletActionContext.getResponse();

        this.session = request.getSession(false);

        /*
         * Check Login
         */
        if (session == null || session.getAttribute("login") == null) {

            try {
                response.sendRedirect("login.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }

            return;
        }

        /*
         * Session Values
         */
        String shopId = (String) this.getSessionMap().get("shopId");
        String shopCode = (String) this.getSessionMap().get("shopCode");
        String db = (String) this.getSessionMap().get("db");

        String shopName = (String) this.getSessionMap().get("shopnameenglish");

        if (shopName == null || shopName.trim().isEmpty()) {
            shopName = "SHOP BILLING";
        }

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        PDDocument document = null;
        PDPageContentStream contentStream = null;

        try {

            /*
             * Database Connection
             */
            connection = GetDBConnection.getDBConnection(db);

            /*
             * Get all active salesmen
             *
             * Same shop_id and shop_code as logged-in shop
             */
            String sql =
                    "SELECT "
                    + "salesman_id, "
                    + "salesman_name, "
                    + "mobile_number, "
                    + "commission_percentage, "
                    + "active "
                    + "FROM shop_salesman_master "
                    + "WHERE shop_id = ? "
                    + "AND shop_code = ? "
                    + "AND active = 'Y' "
                    + "ORDER BY salesman_name";

            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1, shopId);
            preparedStatement.setString(2, shopCode);

            resultSet = preparedStatement.executeQuery();

            /*
             * Create PDF
             */
            document = new PDDocument();

            PDPage page = new PDPage(PDRectangle.A4);

            document.addPage(page);

            contentStream = new PDPageContentStream(document, page);

            int pageCount = 1;

            /*
             * Create Header Table
             */
            Table header = createHeaderTable(shopName, pageCount);

            float startY =
                    page.getMediaBox().getHeight() - PADDING20;

            float currentY = startY;

            /*
             * Draw Header
             */
            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(header)
                    .startX(PADDING30)
                    .startY(startY)
                    .build()
                    .draw();

            /*
             * Create Salesman Table
             *
             * Total width = 80 + 180 + 120 + 100 + 105 = 585
             */
            TableBuilder salesmanTableBuilder =
                    createSalesmanTableHeader();

            int rowCount = 0;

            /*
             * Read salesman records
             */
            while (resultSet.next()) {

                /*
                 * If there is not enough space for another row,
                 * draw current table and create a new page.
                 */
                if (currentY < 100) {

                    Table salesmanTable =
                            salesmanTableBuilder.build();

                    TableDrawer.builder()
                            .contentStream(contentStream)
                            .table(salesmanTable)
                            .startX(PADDING5)
                            .startY(startY - 70)
                            .build()
                            .draw();

                    contentStream.close();

                    /*
                     * New Page
                     */
                    pageCount++;

                    page = new PDPage(PDRectangle.A4);

                    document.addPage(page);

                    contentStream =
                            new PDPageContentStream(document, page);

                    currentY =
                            page.getMediaBox().getHeight() - PADDING20;

                    /*
                     * New Header
                     */
                    header = createHeaderTable(shopName, pageCount);

                    TableDrawer.builder()
                            .contentStream(contentStream)
                            .table(header)
                            .startX(PADDING30)
                            .startY(currentY)
                            .build()
                            .draw();

                    /*
                     * Reset salesman table
                     */
                    salesmanTableBuilder =
                            createSalesmanTableHeader();

                    currentY = currentY - 70;
                }

                /*
                 * Read values
                 */
                String salesmanId =
                        String.valueOf(
                                resultSet.getInt("salesman_id"));

                String salesmanName =
                        resultSet.getString("salesman_name");

                String mobileNumber =
                        resultSet.getString("mobile_number");

                String commission =
                        String.format(
                                "%.2f",
                                resultSet.getDouble(
                                        "commission_percentage"));

                String active =
                        resultSet.getString("active");

                /*
                 * Handle NULL values
                 */
                if (salesmanName == null) {
                    salesmanName = "";
                }

                if (mobileNumber == null) {
                    mobileNumber = "";
                }

                if (active == null) {
                    active = "";
                }

                /*
                 * Add Salesman Row
                 */
                Row salesmanRow = Row.builder()

                        .add(
                            TextCell.builder()
                                .text(salesmanId)
                                .horizontalAlignment(CENTER)
                                .borderWidth(0.5F)
                                .lineSpacing(1F)
                                .build()
                        )

                        .add(
                            TextCell.builder()
                                .text(salesmanName)
                                .horizontalAlignment(LEFT)
                                .borderWidth(0.5F)
                                .lineSpacing(1F)
                                .build()
                        )

                        .add(
                            TextCell.builder()
                                .text(mobileNumber)
                                .horizontalAlignment(LEFT)
                                .borderWidth(0.5F)
                                .lineSpacing(1F)
                                .build()
                        )

                        .add(
                            TextCell.builder()
                                .text(commission)
                                .horizontalAlignment(RIGHT)
                                .borderWidth(0.5F)
                                .lineSpacing(1F)
                                .build()
                        )

                        .add(
                            TextCell.builder()
                                .text(active)
                                .horizontalAlignment(CENTER)
                                .borderWidth(0.5F)
                                .lineSpacing(1F)
                                .build()
                        )

                        .backgroundColor(WHITE)
                        .textColor(Color.BLACK)
                        .font(HELVETICA)
                        .fontSize(9)
                        .horizontalAlignment(CENTER)
                        .height(25F)
                        .build();

                salesmanTableBuilder.addRow(salesmanRow);

                currentY = currentY - 25;

                rowCount++;
            }

            /*
             * If no salesman found
             */
            if (rowCount == 0) {

                Row noDataRow = Row.builder()

                        .add(
                            TextCell.builder()
                                .text("No salesman found")
                                .colSpan(5)
                                .horizontalAlignment(CENTER)
                                .borderWidth(0.5F)
                                .build()
                        )

                        .backgroundColor(WHITE)
                        .textColor(Color.BLACK)
                        .font(PDType1Font.HELVETICA)
                        .fontSize(10)
                        .horizontalAlignment(CENTER)
                        .height(30F)
                        .build();

                salesmanTableBuilder.addRow(noDataRow);
            }

            /*
             * Build final table
             */
            Table salesmanTable =
                    salesmanTableBuilder.build();

            /*
             * Draw final salesman table
             */
            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(salesmanTable)
                    .startX(PADDING5)
                    .startY(startY - 70)
                    .build()
                    .draw();

            /*
             * Close content stream
             */
            contentStream.close();

            /*
             * PDF File Path
             */
            String path =
                    request.getSession()
                            .getServletContext()
                            .getRealPath("/images/");

            File directory = new File(path);

            if (!directory.exists()) {
                directory.mkdirs();
            }

            String fileName =
                    "salesman-list-report.pdf";

            String filePath =
                    path + "/" + fileName;

            /*
             * Save PDF
             */
            document.save(filePath);

            document.close();

            /*
             * Send PDF to Browser
             */
            response.reset();

            response.setContentType("application/pdf");

            response.setHeader(
                    "Content-Disposition",
                    "inline; filename=\"" + fileName + "\""
            );

            File pdfFile = new File(filePath);

            response.setContentLengthLong(pdfFile.length());

            FileInputStream fileInputStream =
                    new FileInputStream(pdfFile);

            OutputStream outputStream =
                    response.getOutputStream();

            byte[] buffer = new byte[4096];

            int bytesRead;

            while ((bytesRead =
                    fileInputStream.read(buffer)) != -1) {

                outputStream.write(
                        buffer,
                        0,
                        bytesRead
                );
            }

            outputStream.flush();

            fileInputStream.close();
            outputStream.close();

        } catch (SQLException e) {

            e.printStackTrace();

            try {

                response.sendError(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Database error while generating salesman report."
                );

            } catch (IOException ex) {
                ex.printStackTrace();
            }

        } catch (IOException e) {

            e.printStackTrace();

            try {

                response.sendError(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error while generating salesman PDF."
                );

            } catch (IOException ex) {
                ex.printStackTrace();
            }

        } finally {

            /*
             * Close ResultSet
             */
            if (resultSet != null) {

                try {
                    resultSet.close();
                } catch (SQLException e) {
                    // Ignore
                }
            }

            /*
             * Close PreparedStatement
             */
            if (preparedStatement != null) {

                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    // Ignore
                }
            }

            /*
             * Close Connection
             */
            if (connection != null) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    // Ignore
                }
            }

            /*
             * Close PDF document if still open
             */
            if (document != null) {

                try {
                    if (document.getNumberOfPages() > 0) {
                        // Document already closed in normal flow.
                    }
                } catch (Exception e) {
                    // Ignore
                }
            }
        }
    }

    /**
     * Creates PDF header.
     */
    private Table createHeaderTable(
            String shopName,
            int pageCount) {

        TableBuilder tableHeaderBuilder =
                Table.builder()

                    .addColumnsOfWidth(585)

                    .font(HELVETICA)

                    .borderColor(Color.BLACK)

                    .horizontalAlignment(CENTER);

        /*
         * Shop Name
         */
        Row headerName =
                Row.builder()

                    .add(
                        TextCell.builder()
                            .text(shopName)
                            .horizontalAlignment(CENTER)
                            .borderWidth(0)
                            .lineSpacing(10F)
                            .build()
                    )

                    .backgroundColor(WHITE)

                    .textColor(Color.BLACK)

                    .font(PDType1Font.HELVETICA_BOLD)

                    .fontSize(18)

                    .horizontalAlignment(CENTER)

                    .build();

        /*
         * Report Name
         */
        Row reportName =
                Row.builder()

                    .add(
                        TextCell.builder()
                            .text(
                                "Salesman List"
                                + "       Page No. : "
                                + pageCount
                            )
                            .borderWidthBottom(0.0F)
                            .horizontalAlignment(CENTER)
                            .build()
                    )

                    .backgroundColor(WHITE)

                    .textColor(Color.BLACK)

                    .font(PDType1Font.HELVETICA_BOLD)

                    .fontSize(11)

                    .horizontalAlignment(CENTER)

                    .build();

        /*
         * Header Information
         */
        Row reportInfo =
                Row.builder()

                    .add(
                        TextCell.builder()
                            .text(
                                "All Active Salesman"
                            )
                            .borderWidthBottom(0.0F)
                            .horizontalAlignment(CENTER)
                            .build()
                    )

                    .backgroundColor(WHITE)

                    .textColor(Color.BLACK)

                    .font(PDType1Font.HELVETICA_BOLD)

                    .fontSize(8)

                    .horizontalAlignment(CENTER)

                    .build();

        tableHeaderBuilder.addRow(headerName);

        tableHeaderBuilder.addRow(reportName);

        tableHeaderBuilder.addRow(reportInfo);

        return tableHeaderBuilder.build();
    }

    /**
     * Creates salesman table and column headings.
     */
    private TableBuilder createSalesmanTableHeader() {

        TableBuilder tableBuilder =
                Table.builder()

                    /*
                     * Total width = 585
                     */
                    .addColumnsOfWidth(
                            80,
                            180,
                            120,
                            100,
                            105
                    )

                    .font(HELVETICA)

                    .borderWidth(0.5F)

                    .borderColor(Color.BLACK)

                    .horizontalAlignment(CENTER);

        /*
         * Column Header
         */
        Row tableHeader =
                Row.builder()

                    .add(
                        TextCell.builder()
                            .text("ID")
                            .horizontalAlignment(CENTER)
                            .borderWidth(0.5F)
                            .lineSpacing(1F)
                            .build()
                    )

                    .add(
                        TextCell.builder()
                            .text("Name")
                            .horizontalAlignment(LEFT)
                            .borderWidth(0.5F)
                            .lineSpacing(1F)
                            .build()
                    )

                    .add(
                        TextCell.builder()
                            .text("Mobile")
                            .horizontalAlignment(LEFT)
                            .borderWidth(0.5F)
                            .lineSpacing(1F)
                            .build()
                    )

                    .add(
                        TextCell.builder()
                            .text("Commission %")
                            .horizontalAlignment(RIGHT)
                            .borderWidth(0.5F)
                            .lineSpacing(1F)
                            .build()
                    )

                    .add(
                        TextCell.builder()
                            .text("Active")
                            .horizontalAlignment(CENTER)
                            .borderWidth(0.5F)
                            .lineSpacing(1F)
                            .build()
                    )

                    .backgroundColor(Color.LIGHT_GRAY)

                    .textColor(Color.BLACK)

                    .font(PDType1Font.HELVETICA_BOLD)

                    .fontSize(9)

                    .horizontalAlignment(CENTER)

                    .build();

        tableBuilder.addRow(tableHeader);

        return tableBuilder;
    }

    /*
     * SessionAware
     */
    @Override
    public void setSession(Map<String, Object> map) {

        sessionMap =
                (SessionMap<String, Object>) map;
    }

    public SessionMap<String, Object> getSessionMap() {
        return sessionMap;
    }

    public void setSessionMap(
            SessionMap<String, Object> sessionMap) {

        this.sessionMap = sessionMap;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(
            HttpServletRequest request) {

        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(
            HttpServletResponse response) {

        this.response = response;
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }
}