// ============================================================================
// File:               $File$
//
// Project:            
//
// Purpose:            
//
// Author:             Rammi
//
// Copyright Notice:   (c) 2005  Rammi (rammi@caff.de)
//                     This code is in the public domain.
//                     Use at own risk.
//                     No guarantees given.
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================
package de.caff.util.settings.swing;

import de.caff.util.settings.DirectoryPreferenceProperty;

import java.io.File;
import java.util.Locale;
import java.util.prefs.Preferences;

/**
 *  Editable directory preference property.
 *
 * @author <a href="mailto:rammi@caff.de">Rammi</a>
 * @version $Revision$
 */
public class SwingDirectoryPreferenceProperty
        extends AbstractBasicSimpleEditablePreferenceProperty
        implements DirectoryPreferenceProperty
{
  /** The directory. */
  private File directory;

  /**
   *  Constructor.
   *  @param basicName  basic name (prefix)
   *  @param baseTag    basic i18n tag
   *  @param directory  default value
   */
  public SwingDirectoryPreferenceProperty(String basicName, String baseTag, File directory)
  {
    super(basicName, baseTag);
    this.directory = directory;
  }

  /**
   * Read the property value from the preferences.
   *
   * @param preferences preferences from where to read the property value
   */
  public void readFrom(Preferences preferences)
  {
    String value = preferences.get(getBasicName(), null);
    if (value != null) {
      setDirectory(new File(value));
    }
  }

  /**
   * Store the current property value in the preferences.
   *
   * @param preferences preferences where to store the property value
   */
  public void storeTo(Preferences preferences)
  {
    if (directory == null) {
      preferences.remove(getBasicName());
    }
    else {
      preferences.put(getBasicName(), directory.getPath());
    }
  }

  /**
   * Get the editor components for editing this preference property.
   *
   * @param l locale used for i18n
   * @return editor components
   */
  public EditorProvider getEditorProvider(Locale l)
  {
    return new DirectoryEditor(this, l);
  }

  /**
   *  Get the directory.
   *  @return the directory
   */
  public File getDirectory()
  {
    return directory;
  }

  /**
   *  Set the directory.
   *  @param directory  the directory
   */
  public void setDirectory(File directory)
  {
    if (directory != null ? !directory.equals(this.directory) : this.directory != null) {
      File oldDirectory = this.directory;
      this.directory = directory;
      fireValueChange(getBasicName(), oldDirectory, directory);
    }
  }
}
