#include "dialog.hpp"

#include <cstring>

namespace game::util
{
  namespace
  {
    const SDL_DialogFileFilter* filters_get(Dialog::Filter filter)
    {
      if (filter == Dialog::NO_FILTER) return nullptr;
      return Dialog::FILTERS[filter];
    }

    int filter_count_get(Dialog::Filter filter)
    {
      if (filter == Dialog::NO_FILTER) return 0;
      return (int)std::size(Dialog::FILTERS[filter]);
    }

    void callback(void* userData, const char* const* filelist, int filter)
    {
      auto* self = (Dialog*)userData;
      if (!self) return;

      if (filelist && filelist[0] && std::strlen(filelist[0]) > 0)
      {
        self->path = filelist[0];
        self->selectedFilter = filter;
      }
      else
      {
        self->path.clear();
        self->selectedFilter = -1;
      }
    }
  }

  Dialog::Dialog(SDL_Window* _window) : window(_window) {}

  void Dialog::window_set(SDL_Window* _window) { window = _window; }

  void Dialog::file_open(Type _type)
  {
    if (_type == NONE) return;
    auto filter = TYPE_FILTERS[_type];
    type = _type;
    path.clear();
    selectedFilter = -1;
    SDL_ShowOpenFileDialog(callback, this, window, filters_get(filter), filter_count_get(filter), nullptr, false);
  }

  void Dialog::file_save(Type _type)
  {
    if (_type == NONE) return;
    auto filter = TYPE_FILTERS[_type];
    type = _type;
    path.clear();
    selectedFilter = -1;
    SDL_ShowSaveFileDialog(callback, this, window, filters_get(filter), filter_count_get(filter), nullptr);
  }

  void Dialog::folder_open(Type _type)
  {
    if (_type == NONE) return;
    type = _type;
    path.clear();
    selectedFilter = -1;
    SDL_ShowOpenFolderDialog(callback, this, window, nullptr, false);
  }

  bool Dialog::is_selected(Type _type) const { return type == _type && !path.empty(); }

  void Dialog::reset()
  {
    auto* currentWindow = window;
    *this = Dialog(currentWindow);
  }
}
