/*

Freely Distributable Java Applets

Copyright (c) 1996-2001 The University of Texas
All Rights Reserved.

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.

The GNU Public License is available in the file LICENSE, or you
can write to the Free Software Foundation, Inc., 59 Temple Place -
Suite 330, Boston, MA 02111-1307, USA, or you can find it on the
World Wide Web at http://www.fsf.org.

Author: Dogu Arifler, Brian Evans, and Saleem Marwat
Version: @(#)LoadFile.java	1.12  04/17/01

Department of Electrical and Computer Engineering
The University of Texas, Austin, TX 78712-1084

*/

package utexas.espl.weds.ui;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Provides dialog box to load a file from an http address
public class LoadFile extends Dialog implements ActionListener {
    private String file = null;
    private String userDirectory = null;

    private JButton loadButton;
    private JButton cancelButton;
    private Label title;
    private Label saveFileTitle;
    private Panel messagePanel;
    private TextArea messageArea = null;
    private TextField urlTextField;
    private TextField filenameTextField;

    private Simulator simulator;

    final int COLUMNS = 30;
    final int GAP = 10;

    // Constructor
    public LoadFile( MainWindow f, Simulator sim ) {
        super( f, "Load a file", false );

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                removeDialog();
            }
        });

        simulator = sim;

        // Create components of the load file applet
        title = new Label( "Enter URL of file to be loaded:" );
        userDirectory = new String(sim.getUserSubDirectory());
        saveFileTitle = new Label( "Save file in " + userDirectory + " as:" );
        filenameTextField = new TextField( COLUMNS );
        urlTextField = new TextField( "http://", COLUMNS );

        loadButton = new JButton( "Load" );
        loadButton.setActionCommand("load");
        loadButton.addActionListener(this);
        cancelButton = new JButton( "Cancel" );
        cancelButton.setActionCommand("cancel");
        cancelButton.addActionListener(this);

        messagePanel = new Panel();
        messagePanel.setLayout( new BorderLayout( GAP, GAP ) );
        Label messageLabel = new Label( "Status of load" );
        messageArea = new TextArea(3, 2*COLUMNS);
        messageArea.setEditable( false );
        messagePanel.add( "Center", messageLabel);
        messagePanel.add( "South", messageArea);

        // Layout components of the load file applet
        Panel fileEntryPanel = new Panel();
        fileEntryPanel.setLayout( new GridLayout(3, 2) );
        fileEntryPanel.add( title );
        fileEntryPanel.add( urlTextField );
        fileEntryPanel.add( saveFileTitle );
        fileEntryPanel.add( filenameTextField );
        fileEntryPanel.add( loadButton );
        fileEntryPanel.add( cancelButton );

        add( "North", fileEntryPanel );
        add( "South", messagePanel );

        // Resize and show the applet window
        setSize( 500, 250 );
        show();

    }

    private void showDialog( String text ) {
        messageArea.setText( new String(text) );
        show();
    }

    // Return true if the passed filename cannot cause any security holes.
    // We want to avoid filenames such as ../../file, so we limit
    // filenames to be composed of letters, digits, underscores, dashes,
    // plus signs, equal signs, periods, and commas.
    private boolean safeFileName( String filename ) {
        boolean returnValue = true;
        int filenameLength = filename.length();
        for (int i = 0; i < filenameLength; i++) {
            char ch = filename.charAt(i);
            boolean validFileNameChar =
               (Character.isLetterOrDigit(ch) || (ch == '_') || (ch == '-') ||
                (ch == '+') || (ch == '=') || (ch == ',') || (ch == '.') ||
                (ch == '~'));
            if (! validFileNameChar) {
                returnValue = false;
                break;
            }
        }
        return returnValue;
    }

    public void actionPerformed( ActionEvent e ) {
        if (e.getSource() instanceof JButton)
          if (e.getActionCommand().equals("cancel")) {
            removeDialog();
        }
        else if ((e.getSource() instanceof TextField) ||
          ((e.getSource() instanceof JButton) && (e.getActionCommand().equals("load")))) {
            String userFilename = new String( filenameTextField.getText() );
            if (userFilename.length() == 0) {
                showDialog( new String("Empty filename given.") );
            }
            else if (!safeFileName(userFilename)) {
                String s =
                    new String( "Filenames must only contain letters, " +
                                "digits, letters, digits, dashes,\n" +
                                "underscores, dashes, plus signs, " +
                                "equal signs, periods, and commas." );
                showDialog( s );
            }
            else {
                if (file != null) {
                    showDialog( new String(
                        "Deleting the previously loaded file ...") );
                    simulator.deleteUserFileOnServer();
                    file = null;
                }
                showDialog( new String(
                    "Trying to load " + userFilename + " ...") );
                file = new String(userFilename);
                String exists = simulator.checkUserFileOnServer(userFilename);
                if (exists.equals("not_exists")) {
                    String s = new String(
                        simulator.loadURLFileToServer(urlTextField.getText()));
                    showDialog( s );
                }
                else if (exists.equals("exists") || exists.equals("Error")) {
                    String s = new String( "Filename already exists." );
                    showDialog( s );
                }
            }
        }
    }

    public void removeDialog() {
        hide();
        dispose();
    }
}
