/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.save.reports.pdf;

import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.save.analytics.ReportChartWrapper;
import com.save.service.PromoDealService;
import com.save.client.serviceprovider.PromoDealServiceImpl;
import com.vaadin.server.StreamResource.StreamSource;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.Spring.width;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author jetberay
 */
public class PromoDealsChartPDF implements StreamSource {

    PromoDealService pds = new PromoDealServiceImpl();
    private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
    Font titleHeader = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
    Font headerFont = FontFactory.getFont("Times-Roman", 10, Font.BOLD);
    Font content = FontFactory.getFont("Times-Roman", 10);
    Font cellContent = FontFactory.getFont("Times-Roman", 8);
    Font boldFont = FontFactory.getFont("Times-Roman", 8, Font.BOLD);
    
    private int year;
    private String areaCode;
    
    public PromoDealsChartPDF(int year, 
            String areaCode) {
        this.year = year;
        this.areaCode = areaCode;
        
        Document document = null; 
        try {
            document = new Document(PageSize.LETTER, 50, 50, 50, 40);
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            
            Paragraph header = new Paragraph();
            header.setAlignment(Element.ALIGN_CENTER);
            header.add(new Phrase("SOCIETY AGRI-VENTURE ENTERPRISE INC.", titleHeader));            
            document.add(header); 

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        
            double totalAmountPerMonth = 0;
            for(int i = 1; i < 13; i++){
                totalAmountPerMonth = pds.findTotalPromoDealsAmountByAreaCode(areaCode, getYear(), i);
                dataset.setValue(totalAmountPerMonth, "Promo Deals", getMonth().get(i));
            }

            JFreeChart chart = ChartFactory.createLineChart(
                    "Promo Deals Report as of "+getYear(), 
                    "Month Period", 
                    "Amount", 
                    dataset, 
                    PlotOrientation.VERTICAL, 
                    true, 
                    true, 
                    false);

            chart.setBackgroundPaint(Color.white);
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
            plot.setBackgroundPaint(Color.lightGray);
            plot.setRangeGridlinePaint(Color.white);

            // customise the range axis...
            NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
            rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

            // customise the renderer...
            LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
            renderer.setShapesVisible(true);
            renderer.setDrawOutlines(true);
            renderer.setUseFillPaint(true);
            renderer.setFillPaint(Color.white);

            CategoryAxis axis = chart.getCategoryPlot().getDomainAxis();
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
            
            /* 2D Chart created till this point, this can be moved into iText PDF */
            int width=640; /* Width of our chart */
            int height=480; /* Height of our chart */

            /* Get Direct Content of the PDF document for writing */
            PdfContentByte Add_Chart_Content= writer.getDirectContent();
            
            /* Create a template using the PdfContent Byte object */
            PdfTemplate template_Chart_Holder=Add_Chart_Content.createTemplate(width,height);
            
            /* Create a 2D graphics object to write on the template */
            Graphics2D Graphics_Chart=template_Chart_Holder.createGraphics(width,height,new DefaultFontMapper());
            
            /* Create a Rectangle object */
            Rectangle2D Chart_Region=new Rectangle2D.Double(0,0,540,380);
            
            /* Invoke the draw method passing the Graphics and Rectangle 2D object to draw the chart */
            chart.draw(Graphics_Chart, Chart_Region);            
            Graphics_Chart.dispose();
            
            /* Add template to PdfContentByte and then to the PDF document */
            Add_Chart_Content.addTemplate(template_Chart_Holder,20,120);
        } catch (DocumentException ex) {
            Logger.getLogger(PromoDealsChartPDF.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            document.close();
        }
            
    }

    public int getYear() {
        return year;
    }

    public String getAreaCode() {
        return areaCode;
    }

    @Override
    public InputStream getStream() {
        return new ByteArrayInputStream(outputStream.toByteArray());
    }
    
    private Map<Integer, String> getMonth(){
        Map<Integer, String> monthList = new HashMap();
        monthList.put(1, "January");
        monthList.put(2, "February");
        monthList.put(3, "March");
        monthList.put(4, "April");
        monthList.put(5, "May");
        monthList.put(6, "June");
        monthList.put(7, "July");
        monthList.put(8, "August");
        monthList.put(9, "September");
        monthList.put(10, "October");
        monthList.put(11, "November");
        monthList.put(12, "December");
        
        return monthList;
    }
}
