#include <FL/fl_draw.H>

#include <fstream>

#include "clickablebox.hh"
#include "../fe/background.hh"

fe::ClickableBox *fe::ClickableBox::lastSelected = nullptr;

namespace fe {
  int ClickableBox::handle(int event) {
    switch (event) {
      case FL_PUSH:
        if (!imagePath.empty()) {
          if (lastSelected && lastSelected != this) {
            lastSelected->isSelected = false;
            lastSelected->redraw();
          }

          isSelected = true;
          lastSelected = this;
          redraw();

          background = std::make_unique<uw::Background>(imagePath);
          background->setWallpaper(fe::Background().getMode());
          alterXinitrc(getImagePath());
        }
        return 1;
      default:
        return Fl_Box::handle(event);
    }
  }

  void ClickableBox::draw() {
    Fl_Box::draw();

    if (isSelected) {
      fl_color(234, 121, 216);
      fl_line_style(FL_SOLID, 9);
      fl_rect(x(), y(), w(), h());
      fl_line_style(0);
    }
  }

  void ClickableBox::alterXinitrc(const std::string &npath) {
    const std::string xinitrc = std::string(getenv("HOME")) + "/.xinitrc";
    std::ifstream in(xinitrc);
    std::vector<std::string> lines;
    std::string line;
    bool founduw = false;
    bool addeduw = false;

    std::string modeFlag;
    switch(fe::Background().getMode()) {
      case uw::Mode::TILE: modeFlag = "-t"; break;
      case uw::Mode::CENTER: modeFlag = "-c"; break;
      case uw::Mode::FILL: modeFlag = "-f"; break;
      default: modeFlag = "-t"; break;
    }

    while (std::getline(in, line)) {
      if (line.rfind("uw -", 0) == 0) {
        line = "uw " + modeFlag + " " + npath + " &";
        founduw = true;
      }
      lines.push_back(line);

      if (line.rfind("exec ", 0) == 0 && !founduw && !addeduw) {
        lines.insert(lines.end() - 1, "uw " + modeFlag +  " " + npath + " &");
        addeduw = true;
      }
    }
    in.close();

    if (!founduw && !addeduw) {
      lines.push_back("uw " + modeFlag + " " + npath + " &");
    }

    std::ofstream out(xinitrc);
    for (const auto &eline : lines) {
      out << eline << std::endl;
    }
    out.close();
  }
}
