/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  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
 * 
 *  --- CVS Information ---
 *  $Id: DirectoriesPane.java,v 1.13 2004/07/09 19:37:47 gregork Exp $
 */
package phex.gui.dialogs.options;

import java.awt.event.*;
import java.io.File;
import java.util.HashMap;

import javax.swing.*;

import phex.common.ServiceManager;
import phex.gui.common.GUIUtils;
import phex.share.*;
import phex.utils.*;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.*;

public class DirectoriesPane extends OptionsSettingsPane
{
    private static final String DIRECTORY_ERROR_KEY = "DirectoryErrorKey";
    private static final String DOWNLOAD_DIRECTORY_KEY = "DownloadDirectory";
    private static final String INCOMPLETE_DIRECTORY_KEY = "IncompleteDirectory";
    private static final String SHARE_DIRECTORIES_KEY = "ShareDirectories";

    private static final String INCOMPLETE_DIR_SHARED = "IncompleteDirShared";
    private static final String NO_DIRECTORY_SHARED = "NoDirectoryShared";
    private static final String CANT_CREATE_DOWNLOAD_DIR = "CantCreateDownloadDir";
    private static final String CANT_CREATE_INCOMPLETE_DIR = "CantCreateIncompleteDir";

    private JTextField incompleteDirectoryTF;
    private JTextField downloadDirectoryTF;
    private JList sharedDirectoryList;
    private JCheckBox shareSubDirectoriesChkBx;
    private JTextField includeFilesTF;
    private JTextField excludeFilesTF;

    public DirectoriesPane()
    {
        super( "Directories" );
    }

    /**
     * Called when preparing this settings pane for display the first time. Can
     * be overriden to implement the look of the settings pane.
     */
    protected void prepareComponent()
    {
        FormLayout layout = new FormLayout(
            "10dlu, right:d, 2dlu, d:grow, 2dlu, d, 2dlu", // columns
            "p, 3dlu, p, 3dlu, p, 9dlu, " + // rows
            "p, 3dlu, p, 3dlu, p, 15dlu:grow, 3dlu, p, 3dlu, p, 3dlu, p" ); 
        layout.setRowGroups( new int[][]{{3, 5, 9, 11, 14, 16, 18}} );
        
        //setLayout( new BorderLayout() );
        //JPanel contentPanel = new FormDebugPanel();
        //add( contentPanel, BorderLayout.CENTER );
        
        //PanelBuilder builder = new PanelBuilder( contentPanel, layout );
        PanelBuilder builder = new PanelBuilder( this, layout );
        CellConstraints cc = new CellConstraints();
        
        builder.addSeparator( Localizer.getString( "DirSettings_DownloadFolders" ),
            cc.xywh( 1, 1, 7, 1 ));
        
        builder.addLabel( Localizer.getString( "DirSettings_Incomplete" ) + ": ",
            cc.xy( 2, 3 ) );
        incompleteDirectoryTF = new JTextField( ServiceManager.sCfg.incompleteDir );
        builder.add( incompleteDirectoryTF, cc.xy( 4, 3 ) );
        JButton button = new JButton( Localizer.getString( "DirSettings_SetFolder" ) );
        //button.setMargin( noInsets );
        button.addActionListener( new SetIncompleteDirectoryListener() );
        builder.add( button, cc.xy( 6, 3 ) );
        
        builder.addLabel( Localizer.getString( "DirSettings_Completed" ) + ": ",
            cc.xy( 2, 5 ) );
        downloadDirectoryTF = new JTextField( ServiceManager.sCfg.mDownloadDir );
        builder.add( downloadDirectoryTF, cc.xy( 4, 5 ) );
        button = new JButton( Localizer.getString( "DirSettings_SetFolder" ) );
        //button.setMargin( noInsets );
        button.addActionListener( new SetDownlodDirectoryListener() );
        builder.add( button, cc.xy( 6, 5 ) );
        
        builder.addSeparator( Localizer.getString( "DirSettings_SharedFolders" ),
            cc.xywh( 1, 7, 7, 1 ));

        // take the list from the file administration since its already split
        FileAdministration fileAdmin =
            ShareManager.getInstance().getFileAdministration();
        File[] dirs = fileAdmin.getSharedDirectories();
        DefaultListModel model = new DefaultListModel();
        // TODO in JDK 1.4 there is no better way to fill the DefaultListModel :-(
        for ( int i = 0; i < dirs.length; i++ )
        {
            model.addElement( dirs[i] );
        }
        sharedDirectoryList = new JList( model );
        sharedDirectoryList.setVisibleRowCount( 3 );
        builder.add( new JScrollPane( sharedDirectoryList ), cc.xywh( 2, 9, 3, 4 ) );
        
        button = new JButton( Localizer.getString( "Add" ) );
        //button.setMargin( noInsets );
        button.addActionListener( new AddUploadDirectoryListener() );
        builder.add( button, cc.xy( 6, 9 ) );
        
        button = new JButton( Localizer.getString( "Remove" ) );
        //button.setMargin( noInsets );
        button.addActionListener( new ActionListener()
            {
                public void actionPerformed( ActionEvent e )
                {
                    int idx = sharedDirectoryList.getSelectedIndex();
                    if ( idx < 0 )
                    {
                        return;
                    }
                    DefaultListModel model = (DefaultListModel)sharedDirectoryList.getModel();
                    model.removeElementAt( idx );
                }
            } );
        builder.add( button, cc.xy( 6, 11 ) );

        shareSubDirectoriesChkBx = new JCheckBox(
            Localizer.getString( "ShareSubDirectories"),
            ServiceManager.sCfg.mUploadScanRecursively );
        builder.add( shareSubDirectoriesChkBx, cc.xywh( 2, 14, 3, 1 ) );
        
        builder.addLabel( Localizer.getString( "IncludeFiles" ) + ": ",
            cc.xy( 2, 16 ) );
        includeFilesTF = new JTextField( ServiceManager.sCfg.mUploadFileInclusions );
        builder.add( includeFilesTF, cc.xy( 4, 16 ) );
        
        builder.addLabel( Localizer.getString( "ExcludeFiles" ) + ": ",
            cc.xy( 2, 18 ) );
        excludeFilesTF = new JTextField( ServiceManager.sCfg.mUploadFileExclusions );
        builder.add( excludeFilesTF, cc.xy( 4, 18 ) );
    }

    /**
     * Override this method if you like to verify inputs before storing them.
     * A input dictionary is given to the pane. It can be used to store values
     * like error flags or prepared values for saving. The dictionary is given
     * to every settings pane checkInput(), displayErrorMessage() and
     * saveAndApplyChanges() method.
     * When the input has been flaged as invalid with the method setInputValid()
     * the method displayErrorMessage() is called directly after return of
     * checkInput() and the focus is given to settings pane.
     * After checking all settings pane without any error the method
     * saveAndApplyChanges() is called for all settings panes to save the
     * changes.
     */
    public void checkInput( HashMap inputDic )
    {
        File downloadDir = null;
        String downloadDirPath = downloadDirectoryTF.getText();
        downloadDir = new File( downloadDirPath );

        String incompleteDirPath = incompleteDirectoryTF.getText();
        File incompleteDir = new File( incompleteDirPath );

        boolean shareSubDirs = shareSubDirectoriesChkBx.isSelected();
        ListModel model = sharedDirectoryList.getModel();

        int size = model.getSize();
        if ( size == 0 )
        {
            inputDic.put( DIRECTORY_ERROR_KEY, NO_DIRECTORY_SHARED );
            setInputValid( inputDic, false );
            return;
        }

        File[] shareDirs = new File[ size ];
        for ( int i = 0; i < size; i++ )
        {
            File shareDir = (File)model.getElementAt( i );

            // check if is download dir... we don't like sharing download dir...
            boolean isIncompleteDirShared = incompleteDir.equals( shareDir );
            if ( shareSubDirs && !isIncompleteDirShared)
            {
                isIncompleteDirShared = FileUtils.isChildOfDir( incompleteDir,
                    shareDir );
            }
            // download dir is shared...
            if ( isIncompleteDirShared )
            {
                inputDic.put( DIRECTORY_ERROR_KEY, INCOMPLETE_DIR_SHARED );
                setInputValid( inputDic, false );
                return;
            }
            shareDirs[i] = shareDir;
        }

        if ( !downloadDir.exists() || !downloadDir.isDirectory() )
        {
            boolean succ = downloadDir.mkdirs();
            if ( !succ )
            {
                inputDic.put( DIRECTORY_ERROR_KEY, CANT_CREATE_DOWNLOAD_DIR );
                setInputValid( inputDic, false );
                return;
            }
        }

        if ( !incompleteDir.exists() || !incompleteDir.isDirectory())
        {
            boolean succ = incompleteDir.mkdirs();
            if ( !succ )
            {
                inputDic.put( DIRECTORY_ERROR_KEY, CANT_CREATE_INCOMPLETE_DIR );
                setInputValid( inputDic, false );
                return;
            }
        }
        inputDic.put( DOWNLOAD_DIRECTORY_KEY, downloadDir );
        inputDic.put( INCOMPLETE_DIRECTORY_KEY, incompleteDir );
        inputDic.put( SHARE_DIRECTORIES_KEY, shareDirs );
        setInputValid( inputDic, true );
    }

    /**
     * When isInputValid() returns a false this method is called.
     * The input dictionary should contain the settings pane specific information
     * of the error.
     * The settings pane should override this method to display a error
     * message. Before calling the method the focus is given to the
     * settings pane.
     */
    public void displayErrorMessage( HashMap inputDic )
    {
        Object error = inputDic.get( DIRECTORY_ERROR_KEY );
        if ( error == null )
        {// no error
            return;
        }

        if ( error.equals( INCOMPLETE_DIR_SHARED ) )
        {
            incompleteDirectoryTF.requestFocus();
            incompleteDirectoryTF.selectAll();
            GUIUtils.showErrorMessage(
                Localizer.getString( INCOMPLETE_DIR_SHARED ),
                Localizer.getString( "DirectoryError" ) );
        }
        else if ( error.equals( NO_DIRECTORY_SHARED ) )
        {
            GUIUtils.showErrorMessage(
                Localizer.getString( NO_DIRECTORY_SHARED ),
                Localizer.getString( "DirectoryError" ) );
        }
        else if ( error.equals( CANT_CREATE_DOWNLOAD_DIR ) )
        {
            downloadDirectoryTF.requestFocus();
            downloadDirectoryTF.selectAll();
            String[] params = { downloadDirectoryTF.getText() };
            GUIUtils.showErrorMessage(
                Localizer.getFormatedString( CANT_CREATE_DOWNLOAD_DIR, params ),
                Localizer.getString( "DirectoryError" ) );
        }
        else if ( error.equals( CANT_CREATE_INCOMPLETE_DIR ) )
        {
            incompleteDirectoryTF.requestFocus();
            incompleteDirectoryTF.selectAll();
            String[] params = { incompleteDirectoryTF.getText() };
            GUIUtils.showErrorMessage(
                Localizer.getFormatedString( CANT_CREATE_INCOMPLETE_DIR, params ),
                Localizer.getString( "DirectoryError" ) );
        }
    }

    /**
     * Override this method if you like to apply and save changes made on
     * settings pane. To trigger saving of the configuration if any value was
     * changed call triggerConfigSave().
     */
    public void saveAndApplyChanges( HashMap inputDic )
    {
        File downloadDir = (File)inputDic.get( DOWNLOAD_DIRECTORY_KEY );
        String downloadDirPath = downloadDir.getAbsolutePath();
        if ( !ServiceManager.sCfg.mDownloadDir.equals( downloadDirPath ) )
        {
            ServiceManager.sCfg.mDownloadDir = downloadDirPath;
            OptionsSettingsPane.triggerConfigSave( inputDic );
        }

        File incompleteDir = (File)inputDic.get( INCOMPLETE_DIRECTORY_KEY );
        String incompleteDirPath = incompleteDir.getAbsolutePath();
        if ( !ServiceManager.sCfg.incompleteDir.equals( incompleteDirPath ) )
        {
            ServiceManager.sCfg.incompleteDir = incompleteDirPath;
            OptionsSettingsPane.triggerConfigSave( inputDic );
        }

        File[] shareDirs = (File[])inputDic.get( SHARE_DIRECTORIES_KEY );
        StringBuffer shareDirsPaths = new StringBuffer();
        for ( int i = 0; i < shareDirs.length; i++ )
        {
            shareDirsPaths.append( shareDirs[i].getAbsolutePath() );
            shareDirsPaths.append( ';' );
        }
        if ( !ServiceManager.sCfg.mUploadDir.equals( shareDirsPaths.toString() ) )
        {
            ServiceManager.sCfg.mUploadDir = shareDirsPaths.toString();
            OptionsSettingsPane.triggerConfigSave( inputDic );
            OptionsSettingsPane.triggerSharedFilesRescan( inputDic );
        }

        boolean shareSubDirs = shareSubDirectoriesChkBx.isSelected();
        if ( ServiceManager.sCfg.mUploadScanRecursively != shareSubDirs )
        {
            ServiceManager.sCfg.mUploadScanRecursively = shareSubDirs;
            OptionsSettingsPane.triggerConfigSave( inputDic );
            OptionsSettingsPane.triggerSharedFilesRescan( inputDic );
        }


        String inclusions = includeFilesTF.getText();
        if ( !ServiceManager.sCfg.mUploadFileInclusions.equals( inclusions ) )
        {
            ServiceManager.sCfg.mUploadFileInclusions = inclusions;
            OptionsSettingsPane.triggerConfigSave( inputDic );
            OptionsSettingsPane.triggerSharedFilesRescan( inputDic );
        }

        String exclusions = excludeFilesTF.getText();
        if ( !ServiceManager.sCfg.mUploadFileExclusions.equals( exclusions ) )
        {
            ServiceManager.sCfg.mUploadFileExclusions = exclusions;
            OptionsSettingsPane.triggerConfigSave( inputDic );
            OptionsSettingsPane.triggerSharedFilesRescan( inputDic );
        }
    }

    private class AddUploadDirectoryListener implements ActionListener
    {
        public void actionPerformed( ActionEvent e )
        {
            JFileChooser chooser = new JFileChooser();
            DefaultListModel model = (DefaultListModel)sharedDirectoryList.getModel();
            if ( model.getSize() > 0 )
            {
                File dir = (File)model.getElementAt( model.getSize() - 1 );
                chooser.setSelectedFile( dir );
            }
            chooser.setAcceptAllFileFilterUsed( false );
            chooser.setFileFilter( new DirectoryOnlyFileFilter() );
            chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            chooser.setMultiSelectionEnabled( true );
            chooser.setDialogTitle(
                Localizer.getString( "AddUploadDirectories" ) );
            chooser.setApproveButtonText( Localizer.getString( "Add" ) );
            chooser.setApproveButtonMnemonic(
                Localizer.getChar( "AddDirectoryMnemonic" ) );
            int returnVal = chooser.showDialog( DirectoriesPane.this, null );
            if( returnVal == JFileChooser.APPROVE_OPTION )
            {
                File[] files = chooser.getSelectedFiles();
                for ( int i = 0; i < files.length; i++ )
                {
                    if ( !model.contains( files[i] ) )
                    {
                        model.addElement( files[i] );
                    }
                }
            }
        }
    }

    private class SetDownlodDirectoryListener implements ActionListener
    {
        public void actionPerformed( ActionEvent e )
        {
            JFileChooser chooser = new JFileChooser();
            chooser.setSelectedFile( new File( downloadDirectoryTF.getText() ) );
            chooser.setAcceptAllFileFilterUsed( false );
            chooser.setFileFilter( new DirectoryOnlyFileFilter() );
            chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            chooser.setMultiSelectionEnabled( false );
            chooser.setDialogTitle(
                Localizer.getString( "SelectDownloadDirectory" ) );
            chooser.setApproveButtonText( Localizer.getString( "Select" ) );
            chooser.setApproveButtonMnemonic(
                Localizer.getChar( "SelectMnemonic" ) );
            int returnVal = chooser.showDialog( DirectoriesPane.this, null );
            if( returnVal == JFileChooser.APPROVE_OPTION )
            {
                String directory = chooser.getSelectedFile().getAbsolutePath();
                downloadDirectoryTF.setText( directory );
            }
        }
    }

    private class SetIncompleteDirectoryListener implements ActionListener
    {
        public void actionPerformed( ActionEvent e )
        {
            JFileChooser chooser = new JFileChooser();
            chooser.setSelectedFile( new File( incompleteDirectoryTF.getText() ) );
            chooser.setAcceptAllFileFilterUsed( false );
            chooser.setFileFilter( new DirectoryOnlyFileFilter() );
            chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            chooser.setMultiSelectionEnabled( false );
            chooser.setDialogTitle(
                Localizer.getString( "SelectIncompleteDirectory" ) );
            chooser.setApproveButtonText( Localizer.getString( "Select" ) );
            chooser.setApproveButtonMnemonic(
                Localizer.getChar( "SelectMnemonic" ) );
            int returnVal = chooser.showDialog( DirectoriesPane.this, null );
            if( returnVal == JFileChooser.APPROVE_OPTION )
            {
                String directory = chooser.getSelectedFile().getAbsolutePath();
                incompleteDirectoryTF.setText( directory );
            }
        }
    }
}