package main;

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

public class PrintUtilities extends JPanel implements Printable {

	Score score;
	int xPage;
	int yPage;
	PrinterJob pj = PrinterJob.getPrinterJob();
	
	public PrintUtilities() {
	
	}
	
	public void init(Score score, int xPage, int yPage){
		this.score = score;
		this.xPage = xPage;
		this.yPage = yPage;
		pageSetup();
		//this.setName("yo");
	}
	
	public void pageSetup() {
		PageFormat pf  = new PageFormat();
		//figure out how to get this to return user page format
		pf = pj.pageDialog(pj.defaultPage());
		Paper paper = new Paper();
		double margin = 0; 
		paper.setSize(pf.getPaper().getWidth(), pf.getPaper().getHeight());
		paper.setImageableArea(margin, margin, paper.getWidth(), paper.getHeight());
		pf.setPaper(paper);
		pj.setPrintable(this, pf);
		if (pj.printDialog()) {
			try { pj.print(); }
			catch (PrinterException e) {
				System.out.println(e);
			}
		}
	}

	public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
		if (pageIndex >= Rise.X_DIV * Rise.Y_DIV){
			Rise.CURRENT_X_PAGE = xPage;
			Rise.CURRENT_Y_PAGE = yPage;
			return(NO_SUCH_PAGE);
		}
		else {
			Rise.CURRENT_X_PAGE = pageIndex % Rise.X_DIV;
			Rise.CURRENT_Y_PAGE = pageIndex / Rise.X_DIV;
			score.removeAll();
			score.setNotes();
			score.setNoteChoices();
			Graphics2D g2 = (Graphics2D)g;
			disableDoubleBuffering(this);
			g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
			Dimension d = score.getSize();
			double scaleX = pageFormat.getImageableWidth()/d.width;
			double scaleY = pageFormat.getImageableHeight() / d.height;
	        g2.scale(scaleX, scaleY);
			score.paint(g2);
			enableDoubleBuffering(this);
			return(PAGE_EXISTS);
		}
	}
	
	public static void disableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(false);
	}
	
	public static void enableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(true);
	}
	
}