/**
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info:  http://www.jpedal.org
* (C) Copyright 1997-2008, IDRsolutions and Contributors.
*
* 	This file is part of JPedal
*
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


*
* ---------------
* PrintPanel.java
* ---------------
*/
package org.jpedal.examples.simpleviewer.gui.popups;

import java.awt.print.Paper;
import javax.print.attribute.SetOfIntegerSyntax;
import javax.print.attribute.standard.PageRanges;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;

import org.jpedal.PdfDecoder;
import org.jpedal.examples.simpleviewer.paper.PaperSizes;
import org.jpedal.examples.simpleviewer.SimpleViewer;
import org.jpedal.objects.PrinterOptions;
import org.jpedal.utils.Messages;

public class PrintPanel extends javax.swing.JPanel {
    	
   int pageCount, currentPage;
    private boolean okClicked = false;

    private String[] printersList;
        
    private PaperSizes paperDefinitions=new PaperSizes();
    
    private boolean isFirstTime=true;
    
    
    public PrintPanel(String[] printersList, String defaultPrinter, int pageCount, int currentPage) {
        
    	resetDefaults(printersList, defaultPrinter, pageCount, currentPage);
    	
    	isFirstTime=false;
    }

    public void resetDefaults(String[] printersList, String defaultPrinter, int pageCount, int currentPage) {

    	//this.defaultPrinter=defaultPrinter;
    	this.printersList = printersList;
    	this.pageCount = pageCount;
    	this.currentPage = currentPage;

    	initComponents();


    	String paperSizeFlag=System.getProperty("org.jpedal.printPaperSize");
    	if(paperSizeFlag!=null){
    		String[] availablePaperSizes = paperDefinitions.getAvailablePaperSizes();
    		for(int i=0;i<availablePaperSizes.length;i++){
    			if(paperSizeFlag.equals(availablePaperSizes[i])){
    				pageSize.setSelectedItem(availablePaperSizes[i]);
    			}
    		}
    	}
    	/**set selected printer*/
    	String printerFlag=System.getProperty("org.jpedal.defaultPrinter");
    	if(printerFlag!=null){
    		for(int i=0;i<printersList.length;i++){
    			if(printerFlag.equals(printersList[i])){
    				printerName.setSelectedItem(printersList[i]);
    			}
    		}
    	}else{
    		printerName.setSelectedItem(defaultPrinter);
    	} 
    	
    	
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    	
    	if(isFirstTime){
	        buttonGroup1 = new javax.swing.ButtonGroup();
	        printerPanel = new javax.swing.JPanel();
	        jLabel1 = new javax.swing.JLabel();
	        jLabel2 = new javax.swing.JLabel();
	        printerName = new javax.swing.JComboBox();
	        pageSize = new javax.swing.JComboBox();
	        printRangePanel = new javax.swing.JPanel();
	        pagesFrom = new javax.swing.JTextField();
	        printRangeCurrentPage = new javax.swing.JRadioButton();
	        printRangeAll = new javax.swing.JRadioButton();
	        printRangeCurrentView = new javax.swing.JRadioButton();
	        printRangeFrom = new javax.swing.JRadioButton();
	        jLabel4 = new javax.swing.JLabel();
	        printRangeSubset = new javax.swing.JComboBox();
	        printRangeReversePages = new javax.swing.JCheckBox();
	        jLabel7 = new javax.swing.JLabel();
	        pagesTo = new javax.swing.JTextField();
	        pageHandlingPanel = new javax.swing.JPanel();
	        jLabel8 = new javax.swing.JLabel();
	        printHandlingCopies = new javax.swing.JSpinner();
	        jLabel9 = new javax.swing.JLabel();
	        printHandlingScaling = new javax.swing.JComboBox();
	        autoRotateCenter = new javax.swing.JCheckBox();
	        paperSourceByPDF = new javax.swing.JCheckBox();
	        printToFile = new javax.swing.JCheckBox();
	        okButton = new javax.swing.JButton();
	        
	        cancelButton = new javax.swing.JButton();
	
    	}else
    		this.removeAll();
        
        setLayout(null);

        printerPanel.setLayout(null);

        printerPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, 
        Messages.getMessage("PdfViewerLabel.Printer"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, 
        javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 255)));
        
        jLabel1.setText(Messages.getMessage("PdfViewerPrint.Name"));
        printerPanel.add(jLabel1);
        jLabel1.setBounds(10, 20, 60, 14);

        jLabel2.setText(Messages.getMessage("PdfViewerPrint.PageSize"));
        printerPanel.add(jLabel2);
        jLabel2.setBounds(10, 50, 70, 14);

        printerName.setModel(new javax.swing.DefaultComboBoxModel(printersList));
        printerPanel.add(printerName);
        printerName.setBounds(80, 20, 220, 22);

        pageSize.setModel(new javax.swing.DefaultComboBoxModel(getAvailablePaperSizes()));
        pageSize.setSelectedIndex(paperDefinitions.getDefaultPageIndex());
      
        printerPanel.add(pageSize);
        pageSize.setBounds(80, 50, 220, 22);

        add(printerPanel);
        printerPanel.setBounds(10, 10, 420, 90);

        printRangePanel.setLayout(null);

        printRangePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, 
        		Messages.getMessage("PdfViewerLabel.PrintRange"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, 
        javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(
        		"Tahoma", 0, 11), new java.awt.Color(0, 0, 255)));
        
        pagesFrom.setText("1");
        pagesFrom.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                pagesBoxPressed(evt);
            }
        });

        printRangePanel.add(pagesFrom);
        pagesFrom.setBounds(130, 80, 60, 19);

        buttonGroup1.add(printRangeCurrentPage);
        printRangeCurrentPage.setText(Messages.getMessage("PdfViewerRadioButton.CurrentPage"));
        printRangeCurrentPage.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printRangeCurrentPage.setMargin(new java.awt.Insets(0, 0, 0, 0));
        printRangeCurrentPage.setOpaque(false);
        printRangeCurrentPage.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                currentPageStateChanged(evt);
            }
        });

        printRangePanel.add(printRangeCurrentPage);
        printRangeCurrentPage.setBounds(10, 60, 120, 15);

        buttonGroup1.add(printRangeAll);
        printRangeAll.setSelected(true);
        printRangeAll.setText(Messages.getMessage("PdfViewerRadioButton.All"));
        printRangeAll.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printRangeAll.setMargin(new java.awt.Insets(0, 0, 0, 0));
        printRangeAll.setOpaque(false);
        
        if(isFirstTime){
	        printRangeAll.addItemListener(new java.awt.event.ItemListener() {
	            public void itemStateChanged(java.awt.event.ItemEvent evt) {
	                allStateChanged(evt);
	            }
	        });
        }

        printRangePanel.add(printRangeAll);
        printRangeAll.setBounds(10, 20, 70, 15);

        buttonGroup1.add(printRangeCurrentView);
        printRangeCurrentView.setText(Messages.getMessage("PdfViewerPrint.CurrentView"));
        printRangeCurrentView.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printRangeCurrentView.setEnabled(true);
        printRangeCurrentView.setMargin(new java.awt.Insets(0, 0, 0, 0));
        printRangeCurrentView.setOpaque(false);
        printRangePanel.add(printRangeCurrentView);
        printRangeCurrentView.setBounds(10, 40, 140, 15);
        
        if(isFirstTime){
        	printRangeCurrentView.addItemListener(new java.awt.event.ItemListener() {
	            public void itemStateChanged(java.awt.event.ItemEvent evt) {
	            	printRangeCurrentView(evt);
	                
	            }
	        });
        }

        buttonGroup1.add(printRangeFrom);
        printRangeFrom.setText(Messages.getMessage("PdfViewerPrint.PagesFrom"));
        printRangeFrom.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printRangeFrom.setMargin(new java.awt.Insets(0, 0, 0, 0));
        printRangeFrom.setOpaque(false);
        
        if(isFirstTime){
	        printRangeFrom.addItemListener(new java.awt.event.ItemListener() {
	            public void itemStateChanged(java.awt.event.ItemEvent evt) {
	                pagesFromStateChanged(evt);
	            }
	        });
        }

        printRangePanel.add(printRangeFrom);
        printRangeFrom.setBounds(10, 80, 140, 15);

        jLabel4.setText(Messages.getMessage("PdfViewerPrint.Subset"));
        printRangePanel.add(jLabel4);
        jLabel4.setBounds(10, 110, 100, 14);

        printRangeSubset.setModel(new javax.swing.DefaultComboBoxModel(new String[] { 
        		Messages.getMessage("PdfViewerPrint.AllPagesInRange"), Messages.getMessage("PdfViewerPrint.OddPagesOnly")
        		, Messages.getMessage("PdfViewerPrint.EvenPagesOnly") }));
        printRangePanel.add(printRangeSubset);
        printRangeSubset.setBounds(130, 110, 190, 22);

        printRangeReversePages.setText(Messages.getMessage("PdfViewerPrint.ReversePages"));
        printRangeReversePages.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printRangeReversePages.setMargin(new java.awt.Insets(0, 0, 0, 0));
        printRangePanel.add(printRangeReversePages);
        printRangeReversePages.setBounds(335, 110, 120, 15);

        jLabel7.setText(Messages.getMessage("PdfViewerPrint.PagesTo"));
        printRangePanel.add(jLabel7);
        jLabel7.setBounds(210, 80, 30, 14);

        pagesTo.setText(String.valueOf(pageCount));
        
        if(isFirstTime){
	        pagesTo.addMouseListener(new java.awt.event.MouseAdapter() {
	            public void mousePressed(java.awt.event.MouseEvent evt) {
	                pagesBoxPressed(evt);
	            }
	        });
        }

        printRangePanel.add(pagesTo);
        pagesTo.setBounds(240, 80, 60, 19);

        add(printRangePanel);
        printRangePanel.setBounds(10, 100, 460, 140);

        pageHandlingPanel.setLayout(null);

        pageHandlingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, 
        Messages.getMessage("PdfViewerLabel.PageHandling"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, 
        javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), 
        new java.awt.Color(0, 0, 255)));
        
        jLabel8.setText(Messages.getMessage("PdfViewerPrint.Copies"));
        pageHandlingPanel.add(jLabel8);
        jLabel8.setBounds(10, 20, 50, 14);

        printHandlingCopies.setModel(new SpinnerNumberModel(1, 1, 1000, 1));
        pageHandlingPanel.add(printHandlingCopies);
        printHandlingCopies.setBounds(90, 20, 60, 20);

        jLabel9.setText(Messages.getMessage("PdfViewerPrint.PageScaling"));
        pageHandlingPanel.add(jLabel9);
        jLabel9.setBounds(10, 50, 120, 14);

        printHandlingScaling.setModel(new javax.swing.DefaultComboBoxModel(PrinterOptions.PRINT_SCALING_OPTIONS));
        printHandlingScaling.setSelectedIndex(PrinterOptions.LAST_SCALING_CHOICE);
        pageHandlingPanel.add(printHandlingScaling);
        printHandlingScaling.setBounds(130, 50, 270, 22);

        autoRotateCenter.setSelected(true);
        autoRotateCenter.setText((Messages.getMessage("PdfViewerPrint.AutoRotateAndCenter")));
        autoRotateCenter.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        autoRotateCenter.setMargin(new java.awt.Insets(0, 0, 0, 0));
        pageHandlingPanel.add(autoRotateCenter);
        autoRotateCenter.setBounds(10, 80, 350, 15);

        paperSourceByPDF.setText(Messages.getMessage("PdfViewerPrint.ChoosePaperByPdfSize"));
        paperSourceByPDF.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        paperSourceByPDF.setMargin(new java.awt.Insets(0, 0, 0, 0));
        pageHandlingPanel.add(paperSourceByPDF);
        paperSourceByPDF.setBounds(10, 110, 350, 15);

        add(pageHandlingPanel);
        pageHandlingPanel.setBounds(10, 240, 460, 140);

        printToFile.setText(Messages.getMessage("PdfViewerPrint.PrintToFile"));
        printToFile.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        printToFile.setMargin(new java.awt.Insets(0, 0, 0, 0));
        add(printToFile);
        printToFile.setBounds(20, 390, 160, 15);
        printToFile.setEnabled(false);
        
        okButton.setText(Messages.getMessage("PdfMessage.Ok"));
        
        if(isFirstTime){
	        okButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                okEvent(evt);
	            }
	        });
        }

        add(okButton);
        okButton.setBounds(230, 420, 90, 23);

        cancelButton.setText(Messages.getMessage("PdfMessage.Cancel"));
        
        if(isFirstTime){
	        cancelButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                cancelEvent(evt);
	            }
	        });
        }

        add(cancelButton);
        cancelButton.setBounds(340, 420, 90, 23);
        

    }// </editor-fold>

	private void pagesBoxPressed(java.awt.event.MouseEvent evt) {
        printRangeFrom.setSelected(true);
        printRangeSubset.setEnabled(true);
        printRangeReversePages.setEnabled(true);
    }

    private void pagesFromStateChanged(java.awt.event.ItemEvent evt) {
        if(printRangeFrom.isSelected()){
            printRangeSubset.setEnabled(true);
            printRangeReversePages.setEnabled(true);
        }
    }
    
    private void printRangeCurrentView(java.awt.event.ItemEvent evt) {
        if(printRangeCurrentView.isSelected()){
            printRangeSubset.setEnabled(false);
            printRangeReversePages.setEnabled(false);
        }
    }

    private void currentPageStateChanged(java.awt.event.ItemEvent evt) {
        if(printRangeCurrentPage.isSelected()){
            printRangeSubset.setEnabled(false);
            printRangeReversePages.setEnabled(false);
        }
    }

    private void allStateChanged(java.awt.event.ItemEvent evt) {
        if(printRangeAll.isSelected()){
            printRangeSubset.setEnabled(true);
            printRangeReversePages.setEnabled(true);
        }
    }

    private void cancelEvent(java.awt.event.ActionEvent evt) {                             
        okClicked = false;
        getTopLevelAncestor().setVisible(false);
    }                            

    private void okEvent(java.awt.event.ActionEvent evt) {                         
        okClicked = true;
	getTopLevelAncestor().setVisible(false);
    }                        
    
    
    // Variables declaration - do not modify
    private javax.swing.JCheckBox autoRotateCenter;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JButton okButton;
    private javax.swing.JPanel pageHandlingPanel;
    private javax.swing.JComboBox pageSize;
    private javax.swing.JTextField pagesFrom;
    private javax.swing.JTextField pagesTo;
    private javax.swing.JCheckBox paperSourceByPDF;
    private javax.swing.JSpinner printHandlingCopies;
    private javax.swing.JComboBox printHandlingScaling;
    private javax.swing.JRadioButton printRangeAll;
    private javax.swing.JRadioButton printRangeCurrentPage;
    private javax.swing.JRadioButton printRangeCurrentView;
    private javax.swing.JRadioButton printRangeFrom;
    private javax.swing.JPanel printRangePanel;
    private javax.swing.JCheckBox printRangeReversePages;
    private javax.swing.JComboBox printRangeSubset;
    private javax.swing.JCheckBox printToFile;
    private javax.swing.JComboBox printerName;
    private javax.swing.JPanel printerPanel;
    // End of variables declaration

    /**
     * return range as SetOfIntegerSytax
     * - if you try to do something silly like print all
     *  even pages in rage 1-1 you will get null returned
     */
   public SetOfIntegerSyntax getPrintRange(){
    	
       SetOfIntegerSyntax pageRange = null;
       
       if(printRangeAll.isSelected()){
    	   
    	   pageRange = new PageRanges(1, pageCount);
    	   
           if(printRangeSubset.getSelectedIndex() == 0)
        	   return pageRange;

           if(printRangeSubset.getSelectedIndex() == 1){
        	   String members = "";
               int i = -1;
               while ((i = pageRange.next(i)) != -1) {
                   if(i % 2 == 1){
                       members += i+",";
                   }
               }
               
               StringBuffer sb = new StringBuffer(members);
               sb.deleteCharAt(members.length() - 1);
               members = sb.toString();
               
               pageRange = new PageRanges(members);
           }else if(printRangeSubset.getSelectedIndex() == 2){
        	   String members = "";
               int i = -1;
               while ((i = pageRange.next(i)) != -1) {
                   if(i % 2 == 0){
                       members += i+",";
                   }
               }
               
               StringBuffer sb = new StringBuffer(members);
               sb.deleteCharAt(members.length() - 1);
               members = sb.toString();
               
               pageRange = new PageRanges(members);
           }
           
       }else if(printRangeCurrentPage.isSelected()){
    	   
           pageRange = new PageRanges(currentPage);
           
       }else if(printRangeCurrentView.isSelected()){    
           
    	   pageRange = new PageRanges(currentPage);
    	   
       }else if(printRangeFrom.isSelected()){
    	   
           int start = Integer.parseInt(pagesFrom.getText());
           int end = Integer.parseInt(pagesTo.getText());
           
           if(start>end){
        	   int tmp=end;
        	   end=start;
        	   start=tmp;

               if(SimpleViewer.showMessages)
        	   JOptionPane.showMessageDialog(this,Messages.getMessage("PdfViewerPrint.SwapValues"));
           }
           pageRange = new PageRanges(start,end);
           
           if(printRangeSubset.getSelectedIndex() == 0)
        	   return pageRange;

           if(printRangeSubset.getSelectedIndex() == 1){
        	   String members = "";
               int i = -1;
               while ((i = pageRange.next(i)) != -1) {
                   if(i % 2 == 1){
                       members += i+",";
                   }
               }
               
               StringBuffer sb = new StringBuffer(members);
               sb.deleteCharAt(members.length() - 1);
               members = sb.toString();
               
               pageRange = new PageRanges(members);
           }else if(printRangeSubset.getSelectedIndex() == 2){
        	   String members = "";
               int i = -1;
               while ((i = pageRange.next(i)) != -1) {
                   if(i % 2 == 0){
                       members += i+",";
                   }
               }
               
               StringBuffer sb = new StringBuffer(members);
               int length=members.length();
               if(length>0)
               sb.deleteCharAt(length - 1);
               members = sb.toString();
               
               if(members.length()>0)
               	   pageRange = new PageRanges(members);
               else
            	   pageRange=null;
           }
       }
       
       return pageRange;
    }
    
    public int getCopies(){
    	String copies = printHandlingCopies.getValue().toString();
    	return Integer.parseInt(copies);
    }
    
    /** return setting for type of scaling to use 
     * PAGE_SCALING_NONE,PAGE_SCALING_FIT_TO_PRINTER_MARGINS,PAGE_SCALING_REDUCE_TO_PRINTER_MARGINS
     *see org.jpedal.objects.contstants.PrinterOptions for all values
     */
    public int getPageScaling(){
    	
    	int option=printHandlingScaling.getSelectedIndex();
		
		int value=0;
		//make choice
		switch (option) {
		case 0: //No scaling
			value=PrinterOptions.PAGE_SCALING_NONE;
			break;
			
		case 1: //Fit to scaling
			value=PrinterOptions.PAGE_SCALING_FIT_TO_PRINTER_MARGINS;
			break;
			
		case 2: //Reduce to scaling
			value=PrinterOptions.PAGE_SCALING_REDUCE_TO_PRINTER_MARGINS;
			break;
			
		}
		
		//remember last option for next print dialog
		PrinterOptions.LAST_SCALING_CHOICE=value;
		
    	return value;
    }
    
    public String getPrinter(){
    	return printerName.getSelectedItem().toString();
    }
    
    public boolean okClicked(){
    	return okClicked;
    }
    
    public boolean isAutoRotateAndCenter(){
    	return autoRotateCenter.isSelected();
    }
    
    public boolean isPaperSourceByPDFSize(){
    	return paperSourceByPDF.isSelected();
    }
    
    public boolean isPrintingCurrentView(){
    	return printRangeCurrentView.isSelected();
    }
    
    public String[] getAvailablePaperSizes(){
    	return paperDefinitions.getAvailablePaperSizes();
    }
    
    /**return selected Paper*/
    public Paper getSelectedPaper() {
        return paperDefinitions.getSelectedPaper(pageSize.getSelectedItem());
    }
    
    public boolean isPagesReversed(){
        return printRangeReversePages.isSelected();
    }

	public boolean isOddPagesOnly() {
		return printRangeSubset.getSelectedIndex() == 1;
	}

	public boolean isEvenPagesOnly() {
		return printRangeSubset.getSelectedIndex() == 2;
	}
}
