# -*- coding: utf-8 -*-
#
# File: commonsdialog.py
#
# Copyright (c) 2011 by Model Driven Development sl and Antonio Carrasco Valero
#
# GNU General Public License (GPL)
#
# 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 3
# 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.
#
#

__docformat__ = 'plaintext'


from javax.swing import JFileChooser
from javax.swing.filechooser import FileNameExtensionFilter
from java.lang import Throwable
from java.io import File

#from org.gvsig.app import ApplicationLocator

from org.gvsig.andami.ui.mdiFrame import DefaultThreadSafeDialogs

#====================================
# SWING

#
#messageType options
FORBIDEN = 0
IDEA= 1
WARNING= 2
QUESTION= 3

#
#Confirmdialog optionType Options
YES_NO = 0
YES_NO_CANCEL = 1
ACCEPT_CANCEL = 2

YES = 0
NO = 1
CANCEL = 2

#filechooser options
OPEN_FILE = 0
OPEN_DIRECTORY = 1
SAVE_FILE = 2

#filechooser selectionMode
FILES_ONLY = JFileChooser.FILES_ONLY
DIRECTORIES_ONLY = JFileChooser.DIRECTORIES_ONLY


def msgbox(message, title="", messageType=IDEA, root=None):
    """Shows a message dialog with ok button only
    :param message: text to present in the dialog
    :param title: title of the dialog
    :param messageType: type of icon to use.
    """
    DefaultThreadSafeDialogs(root).messageDialog(message, title, messageType)


def inputbox(message, title="", messageType=IDEA, initialValue="", root=None):
    """
    Shows a input dialog.
    :param message: text to present in the dialog
    :param title: title of the dialog
    :messageType: type of icon to use
    :initialValue: Initial value of the inputbox
    """
    return DefaultThreadSafeDialogs(root).inputDialog(message, title,
        messageType, initialValue)


def confirmDialog(message, title="", optionType=YES_NO, messageType=IDEA, root=None):
    """
    Create a message dialog with options button
    :param message: text to present in the dialog
    :param title: title of the dialog
    :optionType: bottons to show
    :param messageType: type of icon to use.
    """
    #0: yes/no option
    #1: yes/no/cancelar
    #2: accept/cancel
    return DefaultThreadSafeDialogs(None).confirmDialog(message, title,
        optionType, messageType)

def filechooser(option, title="", initialPath=None,
        multiselection=False, filter = None, fileHidingEnabled=True, root=None):
    """
    Allows configuration parameters to filechooser dialogs
    :int option: file chooser selection mode. Allowed values:
        OPEN_FILE, OPEN_DIRECTORY, SAVE_FILE
    :String title: Window title
    :String initialPath: Initial path to the directory to open in the dialog
    :boolean multiselection: Allow select more than one object.
    :String[] filter: list of acepted extension files ("jpg", "png", "gif")
    :boolean fileHidingEnabled: True if hidden files are not displayed
    """
    #
    #Values for open files dialog
    dialogType = JFileChooser.OPEN_DIALOG
    selectionMode = FILES_ONLY

    if option == SAVE_FILE:
        dialogType = JFileChooser.SAVE_DIALOG
    elif option == OPEN_DIRECTORY:
        selectionMode = DIRECTORIES_ONLY

    initialPath = getJavaFile(initialPath)

    if filter:
        filter = FileNameExtensionFilter("Files", filter)

    files = DefaultThreadSafeDialogs(root).showChooserDialog(
            title,
            dialogType,
            selectionMode,
            multiselection,
            initialPath,
            filter,
            fileHidingEnabled)

    try:
        if files == None:
            return None
        elif len(files) <= 0:
            return None
        elif multiselection==False:
            jfile = files[0]
            if isinstance(jfile, File):
                return jfile.getAbsolutePath()
            elif jfile == None:
                return None
            else:
                raise Exception()
        elif multiselection==True:
            filePaths = []
            for jfile in files:
                if isinstance(jfile, File):
                    try:
                        filePaths.append(jfile.getAbsolutePath())
                    except Throwable, ex:
                        raise IOError(jfile)
                else:
                    raise IOError("Not java.io.File type")
            return filePaths
    except Exception, ex:
        raise IOError(files)

def openFileDialog(title='', initialPath=None, root=None):
    """
    Shows a window dialog to choose one file.
    :param title: Window title. Default ''
    :type title: string
    :param initialPath: Initial path to open in window dialog
    :type initialPath: string
    """

    files = DefaultThreadSafeDialogs(root).showOpenFileDialog(
        title,
        getJavaFile(initialPath))

    if files==None:
        return None

    filePaths = []
    for f in files:
        if isinstance(f, File):
            filePaths.append(f.getAbsolutePath())
        else:
            raise IOError("Not java.io.File type")

    return filePaths


def openFolderDialog(title='', initialPath=None, root=None):
    """
    Shows a window dialog to choose one folder.
    :param title: Window title. Default ''
    :type title: string
    :param initialPath: Initial path to open in window dialog
    :type initialPath: string
    """

    files = DefaultThreadSafeDialogs(None).showOpenDirectoryDialog(
        title,
        getJavaFile(initialPath))

    if files==None:
        return None

    filePaths = []
    for f in files:
        if isinstance(f, File):
            filePaths.append(f.getAbsolutePath())
        else:
            raise IOError("Not java.io.File type")

    return filePaths


def saveFileDialog(title='', initialPath=None, root=None):
    """
    Shows a window dialog to choose one file.
    :param title: Window title. Default ''
    :type title: string
    :param initialPath: Initial path to open in window dialog
    :type initialPath: string
    """

    files = DefaultThreadSafeDialogs(root).showSaveFileDialog(
        title,
        getJavaFile(initialPath)
    )

    if files==None:
        return None

    filePaths = []
    for f in files:
        if isinstance(f, File):
            filePaths.append(f.getAbsolutePath())
        else:
            raise IOError("Not java.io.File type")

    return filePaths


def getJavaFile(path):
    """Returns a java File using parameter path.
    If path doesn't exists looks for user home folder and if can not find it,
    returns path will be gvSIG instance directory.
    """
    #
    #Needs because DefaultThreadSafeDialogs files methods use a java File
    #instance as initialPath parameter
    #
    import os
    from java.io import File

    if isinstance(path,File):
      return path

    if path!=None :
        path = os.path.normpath(path)
        if os.path.exists(path):
            return File(path)

    if os.environ.has_key('HOME'):
        return File(os.environ.get('HOME', os.getcwd()))

    if os.path.exists(os.path.expanduser("~")):
        return File(os.path.expanduser("~"))

    return File(os.getcwd())



