/* PrintBamView
 * created: 2012
 * This file is part of Artemis
 *
 * Copyright(C) 2012  Genome Research Limited
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or(at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */
package uk.ac.sanger.artemis.components.alignment;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

import uk.ac.sanger.artemis.Options;
import uk.ac.sanger.artemis.components.PrintArtemis;
import uk.ac.sanger.artemis.components.StickyFileChooser;

public class PrintBamView
{  
  /**
  * Print to a jpeg or png file
  */
  public static void print(JPanel containerPanel)
  {
    // file chooser
    final StickyFileChooser fc = new StickyFileChooser();
    File fselect = new File(fc.getCurrentDirectory()+
                            System.getProperty("file.separator")+
                            "bamview.png");
    fc.setSelectedFile(fselect);
     
    // file name prefix
    Box YBox = Box.createVerticalBox();
    JLabel labFormat = new JLabel("Select Format:");
    Font font = labFormat.getFont();
    labFormat.setFont(font.deriveFont(Font.BOLD));
    YBox.add(labFormat);

    Box bacross = Box.createHorizontalBox();
    final JComboBox formatSelect = new JComboBox(PrintArtemis.getImageFormats());
    formatSelect.setSelectedItem("png");
    formatSelect.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent arg0)
      {
        String selected;
        if(fc.getSelectedFile() != null)
        {
          selected = fc.getSelectedFile().getAbsolutePath();
          String fmts[] = PrintArtemis.getImageFormats();
          for(int i=0; i<fmts.length; i++)
            selected = selected.replaceAll("."+fmts[i]+"$", "");
        }
        else
          selected = "bamview";
        
        fc.setSelectedFile(new File(selected+"."+
               formatSelect.getSelectedItem()));
      }
    });

    Dimension d = formatSelect.getPreferredSize();
    formatSelect.setMaximumSize(d);
    bacross.add(Box.createHorizontalGlue());
    bacross.add(formatSelect);
    YBox.add(bacross);

    // file prefix & format options
    fc.setAccessory(formatSelect);
    int n = fc.showSaveDialog(null);
    if(n == JFileChooser.CANCEL_OPTION)
      return;

    if(((String)formatSelect.getSelectedItem()).equals("svg"))
    {
      createSVG(fc.getSelectedFile(), containerPanel);
      return;
    }

    try
    {
      javax.imageio.ImageIO.write(
            createImage(containerPanel), 
            (String)formatSelect.getSelectedItem(),
            new File(fc.getSelectedFile().getAbsolutePath()));
    }
    catch(NoClassDefFoundError ex)
    {
      JOptionPane.showMessageDialog(null,
            "This option requires Java 1.9 or higher.");
    }
    catch ( IOException e )
    {
      System.out.println("An error occurred: " + e.getMessage());
      e.printStackTrace();
    }
  }
  
  /**
   * Scalable Vector Graphics (SVG)
   * @param fout
   * @param containerPanel
   */
  private static void createSVG(final File fout, final JPanel containerPanel)
  {
    final DOMImplementation domImpl =
        GenericDOMImplementation.getDOMImplementation();
    final Document doc = domImpl.createDocument(
        "http://www.w3.org/2000/svg", "svg", null);

    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(doc);
    ctx.setComment("Generated by BamView with Batik SVG Generator");
    final SVGGraphics2D svgG = new SVGGraphics2D(ctx, true);
    svgG.setFont(Options.getOptions().getFont());
    svgG.setSVGCanvasSize( containerPanel.getSize() );
    containerPanel.paintAll(svgG);

    try
    {
      final Writer out = new OutputStreamWriter(
          new FileOutputStream(fout), "UTF-8");
      svgG.stream(out, true);
    }
    catch (UnsupportedEncodingException e)
    {
      e.printStackTrace();
    }
    catch (SVGGraphics2DIOException e)
    {
      e.printStackTrace();
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }

    return;
  }
  
  /**
  *  Returns a generated image
  *  @param pageIndex   page number
  *  @return            image
  */
  private static RenderedImage createImage(final JPanel containerPanel)
  {
    // Create a buffered image in which to draw
    BufferedImage bufferedImage = new BufferedImage(
        containerPanel.getWidth(),containerPanel.getHeight(),
                                  BufferedImage.TYPE_INT_RGB);
    // Create a graphics contents on the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();
    containerPanel.paintAll(g2d);
    return bufferedImage;
  }
}