#include <FL/Fl_File_Chooser.H>

#include <cstdlib>

#include "background.hh"
#include "misc.hh"
#include "widget.hh"

std::string fe::Background::sfp;

namespace fe {
  Background::Background() {}
  Background::~Background() {}

  uw::Mode Background::getMode() {
    Fl_Choice *choice = Widget::getModeChoice();
    if (!choice) return uw::Mode::TILE;

    switch (choice->value()) {
      case 0: return uw::Mode::TILE;
      case 1: return uw::Mode::CENTER;
      case 2: return uw::Mode::FILL;
      default: return uw::Mode::TILE;
    }
  }

  void Background::chooseImageCb(Fl_Widget *, void *) {
    const char *homedir = std::getenv("HOME");
    std::string defpath;

    if (homedir) {
      std::string userdir = std::string(homedir) + "/.local/share/wallpapers";
      std::string localusr = "/usr/local/share/wallpapers";
      std::string sysusr = "/usr/share/wallpapers";

      if (Misc::isExist(userdir))       defpath = userdir;
      else if (Misc::isExist(localusr)) defpath = localusr;
      else                              defpath = sysusr;
    }

    Fl_File_Chooser chooser(defpath.c_str(), "*.{png,jpg}",
        Fl_File_Chooser::SINGLE, "画像を御選択下さい・・・");
    chooser.show();

    while (chooser.shown()) Fl::wait();

    if (chooser.value() != nullptr) {
      setFilename(chooser.value());
      Widget::getSetButton()->activate();
    }
  }

  void Background::setWallpaperCb(Fl_Widget *, void *) {
    if (!getFilename().empty()) {
      uw::Background bg(getFilename());
      bg.setWallpaper(getMode());
      Widget::getSetButton()->deactivate();
    }
  }
}
