#include "__whiledir.h"
#include "Exception.h"
#include "__mysql.h"
#include <iostream>
#include <filesystem>
#include <vector>
#include <algorithm>

namespace jet {

   __whiledir::__whiledir(coreutils::ZString &in, coreutils::MString &parent, Global &global) : Tag(in, parent, global) {
      if(!variableDefined("path"))
	throw coreutils::Exception("whiledir tag must specify a path.");
      if(variableDefined("sort") && (variables["sort"] == "true")) {
	 std::vector<std::filesystem::directory_entry> entries;
	 for(auto const &entry : std::filesystem::directory_iterator(variables["path"].str())) 
	   entries.push_back(entry);
	 std::sort(entries.begin(), entries.end(), [](const auto &a, const auto &b) { return a.path() < b.path(); });
	 for(const auto &entry : entries) {
	    if(variableDefined("fullpath"))
	      global.variables[variables["fullpath"]] = entry.path();
	    if(variableDefined("filename"))
	      global.variables[variables["filename"]] = entry.path().filename();
	    if(variableDefined("filenamenoextension"))
	      global.variables[variables["filenamenoextension"]] = entry.path().stem();
	    processContainer(container);
	    container.reset();	    
	 }	 
      } else {	 
	 for(auto const &entry : std::filesystem::directory_iterator(variables["path"].str())) {
	    if(variableDefined("fullpath"))
	      global.variables[variables["fullpath"]] = entry.path();
	    if(variableDefined("filename"))
	      global.variables[variables["filename"]] = entry.path().filename();
	    if(variableDefined("filenamenoextension"))
	      global.variables[variables["filenamenoextension"]] = entry.path().stem();
	    processContainer(container);
	    container.reset();
	 }
      }
      
   }
   
}
