#include "config.h"
#include <Elementary.h>

#include "../Ecrire.h"
#include "ui.h"

typedef struct _File_Selector_Data
{
   Evas_Object *parent;
   Evas_Object *inwin;
   Eina_Bool    save;
   void (*func)(void *, Evas_Object *, void *);
   void *data;
} File_Selector_Data;

static void
_cleaning_cb(void *data, Evas_Object *obj, void *event_info)
{
   char *path;
   const char *error = NULL;
   File_Selector_Data *fsdata = data;
   path = event_info;

   if (fsdata->save)
     {
        if (ecore_file_is_dir(path))
          error = eina_slstr_printf(_("Unable to save to directory '%s'"), path);
     }
   else
     {
        if (ecore_file_is_dir(path))
          error = eina_slstr_printf(_("Unable to open directory '%s'"), path);
     }

   if (error)
     ui_alert_warning_popup(fsdata->parent, error);
   else
     {
        if (path)
          fsdata->func(fsdata->data, obj, path);

        evas_object_del(fsdata->inwin);
        free(fsdata);
     }
}

void
ui_file_open_save_dialog_open(Evas_Object *parent, Eina_Bool save,
                              Evas_Smart_Cb func, void *data)
{
   Evas_Object *fs;
   Evas_Object *inwin;
   File_Selector_Data *fsdata;

   inwin = elm_win_inwin_add(parent);
   evas_object_show(inwin);

   fs = elm_fileselector_add(inwin);
   elm_fileselector_is_save_set(fs, save);
   elm_fileselector_expandable_set(fs, EINA_FALSE);
   elm_fileselector_path_set(fs, getenv("HOME"));
   elm_win_inwin_content_set(inwin, fs);
   evas_object_show(fs);

   fsdata = malloc(sizeof(File_Selector_Data));
   fsdata->parent = parent;
   fsdata->inwin  = inwin;
   fsdata->save   = save;
   fsdata->func   = func;
   fsdata->data   = data;

   evas_object_smart_callback_add(fs, "done", _cleaning_cb, fsdata);
}
