package ru.javastudy.spring.mvc;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import ru.javastudy.spring.cats.Cat;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.List;

/**
 * This view class generates a PDF document 'on the fly' based on the data
 * contained in the model.
 */
public class PDFBuilder extends AbstractITextPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document docIText,
                                    PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // get data model which is passed by the Spring container
        List<Cat> catList = (List<Cat>) model.get("cats");
        docIText.add(new Paragraph("PDF create with Spring framework"));

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100.0f);
        table.setWidths(new float[] {3.0f, 2.0f, 2.0f, 2.0f});
        table.setSpacingBefore(10);

        // define font for table header row
        Font font = FontFactory.getFont(FontFactory.HELVETICA);
        font.setColor(BaseColor.WHITE);

        // define table header cell
        PdfPCell cell = new PdfPCell();
        cell.setBackgroundColor(BaseColor.BLUE);
        cell.setPadding(4);

        // write table header

        cell.setPhrase(new Phrase("Name", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("cat breed", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("Weight", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("Birthday", font));
        table.addCell(cell);

        // write table row data
        for (Cat cat : catList) {
            table.addCell(cat.getName());
            table.addCell(cat.getBreed());
            table.addCell(String.valueOf(cat.getWeight()));
            table.addCell(cat.getBirthday());
        }
        docIText.add(table);
    }
}
