//=============================================================================
// Muster-Loesung mit Rekursion aus der Filesystem-Library

#include <filesystem>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
using namespace std::filesystem;

//-----------------------------------------------------------------------------

using fileinfos = map<string, vector<path>>;

//-----------------------------------------------------------------------------

void searchFilesInPath(const path& searchpath, fileinfos& searches)
{
   recursive_directory_iterator it(searchpath);
   recursive_directory_iterator eit;
   for (; it != eit; ++it)
   {
      const path& p = it->path();
      if (is_regular_file(p))
      {
         fileinfos::iterator fit = searches.find(p.filename().string());
         if (fit != searches.end())
         {
            fit->second.push_back(p);
         }
      }
   }
}

//-----------------------------------------------------------------------------

int main()
{
   cout << "Aufg_13_04_Datei_Suche_V2\n\n";

   cout << "Datei-Suche\n-----------\n\n";
   path searchpath;
   for (string input;;)
   {
      cout << "Geben Sie bitte das Such-Verzeichnis ein: ";
      getline(cin, input);
      searchpath = input;
      if (exists(searchpath) && is_directory(searchpath))
      {
         break;
      }
      cout << '"' << input << "\" ist kein Verzeichnis\n";
   }

   fileinfos searches;
   for (string input;;)
   {
      cout << "Geben Sie bitte die Such-Namen ein: ";
      getline(cin, input);
      if (input.empty())
      {
         break;
      }
      searches[input];
   }

   searchFilesInPath(searchpath, searches);

   cout << '\n';
   for (const auto& [name, pathes] : searches)
   {
      cout << name << "  (" << pathes.size() << " Dateien)\n";
      for (const auto& path : pathes)
      {
         cout << "-> " << path.string() << '\n';
      }
   }
   cout << '\n';
}
