//
//  Pippin.java
//  Pippin
//
//  Created by Johan Forsberg on Wed Aug 27 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//
//	For information on setting Java configuration information, including 
//	setting Java properties, refer to the documentation at
//		http://developer.apple.com/techpubs/java/java.html
//

import java.util.Locale;
import java.util.ResourceBundle;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
//import com.apple.mrj.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.io.*;

public class Pippin extends JFrame implements  ActionListener, DropTargetListener {
                                  //, MRJAboutHandler,
                                  //MRJQuitHandler {

    private Font font = new Font("serif", Font.ITALIC+Font.BOLD, 36);

    static JFrame theWindow;
    protected ResourceBundle resbundle;
    protected AboutBox aboutBox;

    // Declarations for menus
    static final JMenuBar mainMenuBar = new JMenuBar();
	
    protected JMenu fileMenu; 
    protected JMenuItem miOpen;
    protected JMenuItem miClear;
    protected JMenuItem miSaveAs;
	

    class MyListModel extends AbstractListModel {
            ArrayList a;
            
            MyListModel() { a=new ArrayList(); }
            public int getSize() { return a.size(); }
            public Object getElementAt(int i) { return a.get(i); }
            public void add(Object o) {
                a.add(o);
                fireIntervalAdded(this, a.size()-1, a.size()-1);
            }
            public void clear() {
                int s=a.size();
                try { a.clear(); } catch (Exception x) {}
                fireIntervalRemoved(this, 0 ,s-1);
            }
    }
    MyListModel inputFiles=new MyListModel();
    MyListModel outputFiles=new MyListModel();
	
    public void addFileMenuItems() {
        miOpen = new JMenuItem (resbundle.getString("openItem"));
        miOpen.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        fileMenu.add(miOpen).setEnabled(true);
        miOpen.addActionListener(this);
        
        miClear = new JMenuItem (resbundle.getString("clearItem"));
        fileMenu.add(miClear).setEnabled(true);
        miClear.addActionListener(this);
		
        miSaveAs = new JMenuItem (resbundle.getString("saveasItem"));
        fileMenu.add(miSaveAs).setEnabled(true);
        miSaveAs.addActionListener(this);
		
        mainMenuBar.add(fileMenu);
    }

    public void addMenus() {
        fileMenu = new JMenu(resbundle.getString("fileMenu"));
        addFileMenuItems();
        setJMenuBar (mainMenuBar);
    }
    
    // Layout
    JPanel topPanel=new JPanel();
    JLabel usageLabel=new JLabel();
    JCheckBox smartCheckBox=new JCheckBox();
    JPanel middlePanel=new JPanel();
    JPanel leftPanel=new JPanel();
    JPanel rightPanel=new JPanel();
    JLabel leftLabel=new JLabel();
    JLabel rightLabel=new JLabel();
    JScrollPane leftScrollPane=new JScrollPane();
    JScrollPane rightScrollPane=new JScrollPane();
    JList inputList=new JList();
    JList outputList=new JList();
    JPanel bottomPanel=new JPanel();
    JButton makePdbButton=new JButton();
    
    DropTarget drop=new DropTarget();
    PDB pdb=new PDB();
    JFileChooser fc=new JFileChooser();

    public Pippin() {
	
        super("");
	theWindow=this;
        // The ResourceBundle below contains all of the strings used in this application.  ResourceBundles
        // are useful for localizing applications - new localities can be added by adding additional 
        // properties files.  
        try {
            resbundle = ResourceBundle.getBundle ("C64Pippinstrings", Locale.getDefault());
            
            addMenus();
    
            aboutBox = new AboutBox();
            Toolkit.getDefaultToolkit();
    //        MRJApplicationUtils.registerAboutHandler(this);
    //        MRJApplicationUtils.registerQuitHandler(this);
    
            // My code begins
            setTitle(resbundle.getString("appTitle"));
            getContentPane().setLayout(new BorderLayout());
            topPanel.setLayout(new FlowLayout());
            usageLabel.setText(resbundle.getString("usageHint"));
            smartCheckBox.setText(resbundle.getString("smartConversion"));
            smartCheckBox.setSelected(true);
            topPanel.add(smartCheckBox);
            getContentPane().add(topPanel, BorderLayout.NORTH);
            middlePanel.setLayout(new GridLayout(1,2));
            //inputList.setBorder(new BevelBorder(BevelBorder.LOWERED));
            //outputList.setBorder(new BevelBorder(BevelBorder.LOWERED));
            inputList.setToolTipText(resbundle.getString("usageHint"));
            outputList.setToolTipText(resbundle.getString("usageHint"));
            drop.setComponent(inputList);
            drop.addDropTargetListener(this);
            inputList.setModel(inputFiles);
            outputList.setModel(outputFiles);
            leftScrollPane.getViewport().setView(inputList);
            rightScrollPane.getViewport().setView(outputList);
            leftScrollPane.setPreferredSize(new Dimension(100,300));
	    leftLabel.setText("Input");
	    rightLabel.setText("Output");
	    leftPanel.setLayout(new BorderLayout());
	    rightPanel.setLayout(new BorderLayout());
	    leftPanel.add(leftLabel, BorderLayout.NORTH);
	    leftPanel.add(leftScrollPane, BorderLayout.CENTER);
	    rightPanel.add(rightLabel, BorderLayout.NORTH);
	    rightPanel.add(rightScrollPane, BorderLayout.CENTER);
            middlePanel.add(leftPanel);
            middlePanel.add(rightPanel);
            getContentPane().add(middlePanel, BorderLayout.CENTER);
            bottomPanel.setLayout(new FlowLayout());
            makePdbButton.setText(resbundle.getString("makePDB"));
            bottomPanel.add(makePdbButton);
            getContentPane().add(bottomPanel, BorderLayout.SOUTH);
            
            pack();
        } catch (Exception x) {
            x.printStackTrace();
        }
        setVisible(true);
    }

    public void handleAbout() {
        aboutBox.setResizable(false);
        aboutBox.setVisible(true);
        aboutBox.show();
    }

    public void handleQuit() {	
        // Require user to click to exit - see tech note 
        // http://developer.apple.com/qa/qa2001/qa1187.html for more details 
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Show the dialog and act accordingly.
                int result = JOptionPane.showConfirmDialog(null,
                    "Do you really want to quit?",
                    "Really Quit?",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
                if (result == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }
            }
        });

        // Throw IllegalStateException so new thread can execute.  If showing
        // dialog on this thread in 10.2, we would throw upon JOptionPane.NO_OPTION
        throw new IllegalStateException("Quit Pending User Confirmation");
    }

    // ActionListener interface (for menus)
    public void actionPerformed(ActionEvent newEvent) {
        if (newEvent.getActionCommand().equals(miOpen.getActionCommand())) doOpen();
        else if (newEvent.getActionCommand().equals(miClear.getActionCommand())) doClear();
        else if (newEvent.getActionCommand().equals(miSaveAs.getActionCommand())) doSaveAs();

    }
	
    public void doOpen() {
        javax.swing.filechooser.FileFilter ff=new C64FileFilter();
        
        fc.setFileFilter(ff);
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.setMultiSelectionEnabled(true);
        if (fc.showOpenDialog(this)==JFileChooser.CANCEL_OPTION)
            return;
            
        File files[]=fc.getSelectedFiles();
        if (files==null) return;
        
        for (int i=0; i<files.length; i++)
            addInputFile(files[i]);
    }
    
    public void doClear() {
        inputFiles.clear();
        outputFiles.clear();
	pdb.clear();
    }
	
    public void doSaveAs() {
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);
        if (fc.showSaveDialog(this)==JFileChooser.CANCEL_OPTION)
            return;

        File file=fc.getSelectedFile();
        if (file==null) return;

	try {
		pdb.saveAs(file);
	} catch (Exception x) {
		x.printStackTrace();
	}
    }

    public static void main(String args[]) {
        new Pippin();
    }
    
    void addInputFile(File f) {
        if (f.isDirectory())
            inputFiles.add("Folder "+f.getName());
        else
            inputFiles.add(f.getName());
            
        java.util.List l=pdb.addFile(f);
        Iterator i=l.iterator();
        while (i.hasNext()) {
            PDBItem itm=(PDBItem)i.next();
            outputFiles.add(itm.name);
        }
    }

// DnD support
    public void dragEnter(DropTargetDragEvent e) {}
    public void dragExit(DropTargetEvent e) {}
    public void dragOver(DropTargetDragEvent e) {}
    public void dropActionChanged(DropTargetDragEvent e) {}
    public void drop(DropTargetDropEvent e) {
        Transferable t=e.getTransferable();
        if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            e.rejectDrop();
            return;
        }
        Object data;
        try {
            data=t.getTransferData(DataFlavor.javaFileListFlavor);
        } catch (Exception x) {
            System.err.println("Flavor refused?!");
            e.rejectDrop();
            return;
        }
        if (!(data instanceof java.util.List)) {
            System.err.println("Data not a List?!");
            e.rejectDrop();
            return;
        }
        java.util.List l = (java.util.List) data;
        e.dropComplete(true);
        //SwingUtilities.RunLater(new Runnable() {
	//    public void run() {
		for (Iterator i=l.iterator(); i.hasNext(); ) {
			Object item=i.next();
			if (item instanceof File) {
				addInputFile((File) item);
			} else {
				System.err.println("Not a file!");
			}
		}
	//    }
	//}
    }
}
