/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 */

#include "./dir-watcher.hpp"

#include <algorithm>

#include "../infotree/json-serializer.hpp"
#include "../ipcs/file-monitor.hpp"

namespace sh4lt::monitor {
DirWatcher::DirWatcher(fs::path path) : path_(std::move(path)) {}

auto DirWatcher::update() -> bool {
  auto res = true;
  auto old = currents_;
  currents_.clear();
  removed_.clear();
  created_.clear();
  for (auto const& dir_entry : std::filesystem::directory_iterator{path_}) {
    auto soc_path = dir_entry.path();
    if (!fileMonitor::is_unix_socket(soc_path.string(), nullptr)) continue;
    currents_.push_back(soc_path);
    const auto existing_entry = std::find(old.cbegin(), old.cend(), soc_path);
    if (existing_entry == old.cend()) {
      created_.push_back(soc_path);
    } else {
      old.erase(existing_entry);
    }
  }
  for (const auto& it : old) {
    removed_.push_back(it);
  }
  return res;
}

}  // namespace sh4lt::monitor
