/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2005 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS 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 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.BufferedInputStream;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

import fr.gouv.finances.cp.utils.ui.IhmFactory;
import fr.gouv.finances.cp.xemelios.auth.XemeliosUser;
import fr.gouv.finances.cp.xemelios.common.Constants;

/**
 * A propos de l'appli
 * @author chm
 */
public class AboutBox extends JDialog {
	static {
		System.out.println(System.getProperty("os.name"));
		if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
			setDefaultLookAndFeelDecorated(true);
	}

    private static final int ADDITIONAL_HEIGHT = 74;
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 3689916175660234039L;
    public AboutBox(Frame owner) {
        super(owner,"A propos... de "+Constants.NOM_APP);
        initialize();
    }
    private void initialize() {
        setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
        JLayeredPane layer = new JLayeredPane();
        //IhmFactory iF = IhmFactory.newInstance();
        ImageIcon image = IhmFactory.getIconFromResource(ImageResources.ABOUT);
        BufferedImage bi = new BufferedImage(image.getIconWidth(),image.getIconHeight()+ADDITIONAL_HEIGHT,BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = (Graphics2D)bi.getGraphics();
        g.drawImage(image.getImage(),0,0,new ImageObserver() {
            public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {return true;}
        });

        int top = image.getIconHeight();
        int width = image.getIconWidth();

        g.setColor(Color.WHITE);
        g.fillRect(0,top,width,ADDITIONAL_HEIGHT);
        g.setColor(Color.BLACK);
        
        
        ImageIcon logo = IhmFactory.getIconFromResource(ImageResources.EDITEUR);
        g.drawImage(logo.getImage(),width-logo.getIconWidth()-2,top+ADDITIONAL_HEIGHT-logo.getIconHeight()-2,this);
//        g.drawImage(logo.getImage(),width-logo.getIconWidth()-2,top+ADDITIONAL_HEIGHT-logo.getIconHeight()-2,new ImageObserver() {
//            public boolean imageUpdate(Image img, int infoFlags, int x, int y, int width, int height) { return true; }
//        });
System.out.println(logo.getIconHeight());
        Font font = g.getFont().deriveFont(Font.BOLD, 12f);
        ecritLigneCentree(g, getVersionText(),90, width, font, Color.BLACK);
        ecritLigneCentree(g, "Développé par axYus",top + 10, width-logo.getIconWidth()-2, font, Color.BLACK);
        if(getParent() instanceof MainWindow) {
	        XemeliosUser user = ((MainWindow)getParent()).getConnectedUser();
	        ecritLigneCentree(g,"Utilisateur: "+user.getDescription(),top-20,width,font,Color.BLACK);
        }
        font = g.getFont().deriveFont(Font.ITALIC, 12f);
        ecritLigneCentree(g, "pour le compte de la Comptabilité Publique", top+25, width-logo.getIconWidth()-2, font, Color.BLACK);

        JLabel icon = new JLabel(new ImageIcon(bi));
        //JLabel icon = new JLabel(logo);
        icon.setOpaque(true);
        // si on ne definit pas la taille, rien est affiche
        icon.setBounds(0,0,width,top+ADDITIONAL_HEIGHT);
        icon.addMouseListener(new MouseAdapter() {
            @Override
			public void mouseClicked(MouseEvent evt) {
                if(evt.getButton()==MouseEvent.BUTTON3 && evt.isControlDown() && evt.getClickCount()==2) {
                    try {
                        Class c = Class.forName("fr.gouv.finances.cp.xemelios.ui.ia.Plateau");
                        c.newInstance();
                    } catch(Throwable t) {}
                }
            }
        });
        layer.setPreferredSize(new Dimension(width,top+ADDITIONAL_HEIGHT));
        JButton pbFermer = new JButton("Fermer");
        pbFermer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                setVisible(false);
            }
        });
        pbFermer.setBounds((width - pbFermer.getPreferredSize().width - logo.getIconWidth()) / 2, top+45, (int)pbFermer.getPreferredSize().getWidth(),(int)pbFermer.getPreferredSize().getHeight());
        layer.add(icon,new Integer(0));
        layer.add(pbFermer,new Integer(1));

        JPanel pane = new JPanel();
        pane.setLayout(new BoxLayout(pane,BoxLayout.PAGE_AXIS));
        pane.add(layer);
        pane.setOpaque(true);
        setContentPane(pane);
        pack();
        validate();
        Dimension sSz = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension fSz = getSize();
        setLocation((sSz.width - fSz.width) / 2, (sSz.height - fSz.height) / 2);
        setResizable(false);
        setVisible(true);
    }
    
    protected String getVersionText() {
        String ret = "";
        try {
            BufferedInputStream bis = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(ImageResources.VERSION));
            byte[] buf = new byte[bis.available()];
            bis.read(buf);
            ret = new String(buf);
        } catch(Throwable t) {}
        return ret;
    }
    
    protected void ecritLigneCentree(Graphics2D graph, String text, int top, int width, Font font, Color c) {
        Color oldColor = graph.getColor();
        Font oldFont = graph.getFont();
        graph.setFont(font);
        graph.setColor(c);
        
		FontMetrics fm = graph.getFontMetrics();
		StringTokenizer st = new StringTokenizer (text, " -");
		Vector<String> lignes = new Vector<String>();
		String ligne=null, mot;
		while (st.hasMoreTokens()) {
			mot = st.nextToken();
			if (fm.stringWidth(mot)>width)
				throw new IllegalArgumentException ("le mot "+mot+" est trop grand; essayez de trouver un autre mot.");

			// si la ligne en cours + le mot en cours dépassent à droite, on commence une nouvelle ligne avec
			// le mot en cours
			int lenLigne = (ligne==null ? fm.stringWidth(mot) : fm.stringWidth(ligne+" "+mot) );
			if (lenLigne > width) {
				lignes.add (ligne);
				ligne = mot;
			} else {
			    if(ligne==null) ligne = mot;
				else ligne += " "+mot;
			}
		}
		if (!"".equals (ligne)) lignes.add(ligne);

		// calcul de l'interligne
		int hauteurLigne = fm.getAscent()+fm.getDescent();
		int interligne = fm.getLeading();
		// position du texte
		for (int i=0; i<lignes.size(); i++) {
		    ligne = lignes.get(i);
			int len = fm.stringWidth(ligne);
			int x = width/2 - len/2;
			int y = (i+1)*interligne + fm.getAscent()+ (i)*hauteurLigne + top;
			graph.drawString (ligne, x, y);
		}

        graph.setFont(oldFont);
        graph.setColor(oldColor);
    }

    public static void main(String[] args) {
        new AboutBox(null);
    }
}
