# Copyright (C) 2010 Canonical Ltd
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

"""File system interaction widgets.

Widgets provide a simple line edit box and a Browse button that
allows the user to use a standard dialog to select a file or directory.
Currently provides:

    * ExistingFileBrowser - for files that already exist in the file system.

    * FileBrowser - for any file (typically for "Save As" operations).

    * DirectoryBrowser - for selecting directories.
"""

from PyQt4 import QtCore, QtGui

from bzrlib.plugins.explorer.lib.i18n import gettext


class FilesystemBrowser(QtGui.QWidget):
    """A widget for selecting a file or directory in a file system."""

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        self.location = QtGui.QLineEdit()
        browse_button = QtGui.QPushButton(gettext('Browse'))

        QtCore.QObject.connect(browse_button, QtCore.SIGNAL("clicked(bool)"),
            self._do_browse_clicked)

        hlayout = QtGui.QHBoxLayout()
        hlayout.addWidget(self.location)
        hlayout.addWidget(browse_button)
        self.setLayout(hlayout)

    def setText(self, text):
        self.location.setText(text)

    def text(self):
        return self.location.text()

    def _do_browse_clicked(self, event):
        """Implemented in the subclasses."""
        pass

class DirectoryBrowser(FilesystemBrowser):
    def _do_browse_clicked(self, event):
        location = self.location.text()
        fileName = QtGui.QFileDialog.getExistingDirectory(self,
            gettext("Select location"), location);
        if fileName:
            self.location.setText(fileName)

class ExistingFileBrowser(FilesystemBrowser):
    def _do_browse_clicked(self, event):
        location = self.location.text()
        fileName = QtGui.QFileDialog.getOpenFileName(self,
            gettext("Select location"), location);
        if fileName:
            self.location.setText(fileName)

class FileBrowser(FilesystemBrowser):
    def _do_browse_clicked(self, event):
        location = self.location.text()
        fileName = QtGui.QFileDialog.getSaveFileName(self,
            gettext("Select location"), location);
        if fileName:
            self.location.setText(fileName)
