#!/usr/bin/python3
""" Allows you to open a Gtk file dialog from and get the selected file in return

Used by a couple of Cinnamon spices via Javascript

Usage:
    cinnamon-file-dialog {0|1|2} -{p|n|d|f} [path] ...
"""

import sys
from setproctitle import setproctitle
setproctitle("cinnamon-file-dialog")

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

cancelButton = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
typeArg = int(sys.argv[1])
fdType = typeArg % 3
if fdType == 0:
    msg = "Open"
    action = Gtk.FileChooserAction.OPEN
    okButton = (Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
elif fdType == 1:
    msg = "Select Folder"
    action = Gtk.FileChooserAction.SELECT_FOLDER
    okButton = (Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
elif fdType == 2:
    msg = "Save"
    action = Gtk.FileChooserAction.SAVE
    okButton = (Gtk.STOCK_SAVE, Gtk.ResponseType.OK)

buttons = cancelButton + okButton
filechooserdialog = Gtk.FileChooserDialog(title=msg, action=action, buttons=buttons)

for i in range(2, len(sys.argv)):
    if sys.argv[i] == "-p":
        filechooserdialog.set_filename(sys.argv[i + 1])
    elif sys.argv[i] == "-n":
        filechooserdialog.set_current_name(sys.argv[i + 1])
    elif sys.argv[i] == "-d":
        filechooserdialog.set_current_folder(sys.argv[i + 1])
    elif sys.argv[i] == "-f":
        filterList = sys.argv[i + 1].split(",")
        for filterInfo in filterList:
            [name, filters] = filterInfo.split(";")
            filterObj = Gtk.FileFilter()
            filterObj.set_name(name)
            rules = filters.split(":")
            for rule in rules:
                [ftype, value] = rule.split("=")
                if ftype == "m":
                    filterObj.add_mime_type(value)
                elif ftype == "p":
                    filterObj.add_pattern(value)
            filechooserdialog.add_filter(filterObj)

if fdType == 2:
    filechooserdialog.set_do_overwrite_confirmation(True)

if typeArg > 2:
    filechooserdialog.set_select_multiple(True)

response = filechooserdialog.run()
if response == Gtk.ResponseType.OK:
    if typeArg > 2:
        print(filechooserdialog.get_filenames())
    else:
        print(filechooserdialog.get_filename())

filechooserdialog.destroy()
