/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.tools.ant.taskdefs.optional.splash;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.*;

import java.io.*;
import java.net.*;


public class SplashTask extends Task 
{

    protected String imgurl;
    protected String proxy = null;
    protected String user = null;
    protected String password = null;
    protected String port = "80";
    protected int showDuration = 5000;
    protected boolean useProxy = false;

    protected static SplashScreen splash = null;

    public void setImageURL(String imgurl) { this.imgurl = imgurl; }
    public void setUseproxy(boolean useProxy) { this.useProxy = useProxy;}
    public void setProxy(String proxy){this.proxy = proxy;}
    public void setPort(String port){this.port = port;}
    public void setUser(String user){this.user = user;}
    public void setPassword(String password){this.password = password;}
    public void setShowduration(int duration) { this.showDuration = duration;}
   

    public void execute() throws BuildException {
        if(splash != null ) {
            splash.setVisible(false);
            project.removeBuildListener(splash);
            splash.dispose();
            splash = null;
        }
      
        log("Creating new SplashScreen", Project.MSG_VERBOSE);
        DataInputStream din = null;

        try{
            URLConnection conn = null;
    
            if(useProxy &&
               (proxy != null && proxy.length() > 0) &&
               (port != null && port.length() > 0)) {
                
                log("Using proxied Connection",  Project.MSG_DEBUG);
                System.getProperties().put("http.proxySet", "true");
                System.getProperties().put("http.proxyHost", proxy);
                System.getProperties().put("http.proxyPort", port);

                URL url = new URL(imgurl);

                conn = url.openConnection();
                if(user != null && user.length() > 0) {
                    String encodedcreds = new sun.misc.BASE64Encoder().encode((new String(user+":"+password)).getBytes());
                    conn.setRequestProperty("Proxy-Authorization", encodedcreds);
                }

            } else {
                System.getProperties().put("http.proxySet", "false");
                System.getProperties().put("http.proxyHost", "");
                System.getProperties().put("http.proxyPort", "");
                log("Using Direction HTTP Connection", Project.MSG_DEBUG);
                URL url = new URL(imgurl);
                conn = url.openConnection();
            }
            conn.setDoInput(true);
            conn.setDoOutput(false);
    
            din = new DataInputStream(conn.getInputStream());

        // Catch everything - some of the above return nulls, throw exceptions or generally misbehave
        // in the event of a problem etc
            
        }catch(Throwable ioe) {
            log("Unable to download image, trying default Ant Logo",Project.MSG_DEBUG);
            log("(Exception was \""+ioe.getMessage()+"\"", Project.MSG_DEBUG);
            din = new DataInputStream(getClass().getClassLoader().getResourceAsStream("antlogo.gif"));
        }


        //Here we should have some kind of DataInputStream pointing at some kind of Image :-)

        try {

            if(din != null) {

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                int data;
                while((data = din.read()) != -1) bout.write((byte)data);

                din.close();
                log("Got ByteArray, creating splash",  Project.MSG_DEBUG);
                ImageIcon img = new ImageIcon(bout.toByteArray());
        
                splash = new SplashScreen(img);
            } else {
                splash = new SplashScreen("Image Unavailable.");
            }
        
            splash.setVisible(true);
            splash.toFront();
            getProject().addBuildListener(splash);
          Thread.currentThread().sleep(showDuration);
        }catch(Exception e) {
           throw new BuildException(e.getMessage());
        }
    }
}



class SplashScreen extends JWindow implements ActionListener,BuildListener{

    JLabel text;
    JProgressBar pb;
    int total;
    final int min = 0;
    final int max = 200;

    public SplashScreen(String msg) {
        init(null);
        setText(msg);
    }
        
    public SplashScreen(ImageIcon img) {
        init(img);
    }

    protected void init(ImageIcon img) {
       
        JPanel pan = (JPanel)getContentPane();
        JLabel piccy;
        if(img == null ) {
            piccy = new JLabel();
        } else {
            piccy = new JLabel(img);
        }
            
        piccy.setBorder(BorderFactory.createLineBorder(Color.black,1));
        text = new JLabel("Building....", JLabel.CENTER);
        text.setFont(new Font("Sans-Serif", Font.BOLD, 12));
        text.setBorder(BorderFactory.createEtchedBorder());

        pb = new JProgressBar(min, max);
        pb.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        JPanel pan2 = new JPanel();
        pan2.setLayout(new BorderLayout());

        pan2.add(text,BorderLayout.NORTH);
        pan2.add(pb,BorderLayout.SOUTH);

        pan.setLayout(new BorderLayout());
        pan.add(piccy, BorderLayout.CENTER);
        pan.add(pan2, BorderLayout.SOUTH);

        pan.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        pack();

        Dimension size = getSize();
        Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (scr.width - size.width) /2;
        int y = (scr.height - size.height) /2;
        setBounds(x,y,size.width, size.height);

    }


    public void setText(String txt) {
        text.setText(txt);
    }

    public void actionPerformed(ActionEvent a) {
        if(total < max) {
            total++;
        } else {
            total = min;
        }
        pb.setValue(total);
    }

    public void buildStarted(BuildEvent event){ actionPerformed(null);}
    public void buildFinished(BuildEvent event){actionPerformed(null);}
    public void targetStarted(BuildEvent event){actionPerformed(null);}
    public void targetFinished(BuildEvent event){actionPerformed(null);}
    public void taskStarted(BuildEvent event){actionPerformed(null);}
    public void taskFinished(BuildEvent event){actionPerformed(null);}
    public void messageLogged(BuildEvent event){actionPerformed(null);}


}

