// SPDX-License-Identifier: MPL-2.0
#include "vybuild.hpp"
#include <regex>
using namespace std;
namespace fs=filesystem;
string vybuild::parser::root_folder_parsing(const string& root_folder,const string& file) {
  if (root_folder=="%filefolder%") {
    return fs::absolute(fs::path(file)).parent_path().string();
  } else if (root_folder=="%rootcallerfolder%") {
    return fs::absolute(vybuild::vars::get_global_variable("%rootcallerfolder%")).string();
  } else {
    return file;
  }
}
vector<string> vybuild::parser::vector_string_vars(vector<string> vector_in) {
  vector<string> out;
  for (auto arg:vector_in) {
    auto element=arg;
    for (auto var:vybuild::vars::get_global_variables_list()) {
      regex regvar(var);
      arg=regex_replace(arg,regvar,vybuild::vars::get_global_variable(var));
    }
    out.push_back(arg);
  }
  return out;
}
string vybuild::parser::string_vars(string string_in) {
  string out=string_in;
  for (auto var:vybuild::vars::get_global_variables_list()) {
    regex regvar(var);
    out=regex_replace(out,regvar,vybuild::vars::get_global_variable(var));
  }
  return out;
}
vector<string> vybuild::parser::vector_string_path_completions(vector<string> vector_in,string suffix) {
  vector<string> out;
  for (int i=0;i<vector_in.size();i++) {
    if (vector_in[i].ends_with(suffix)) {
      out.push_back(vector_in[i]);
    } else if (vector_in[i].ends_with("**")) {
      for (auto &file:fs::recursive_directory_iterator(vector_in[i].substr(0,vector_in[i].size()-2))) {
        if (file.path().string().ends_with(suffix)) {
          out.push_back(file.path().string());
        }
      }
    } else if (vector_in[i].ends_with("*")) {
      for (auto &file:fs::directory_iterator(vector_in[i].substr(0,vector_in[i].size()-3))) {
        if (file.path().string().ends_with(suffix)) {
          out.push_back(file.path().string());
        }
      }
    }
  }
  return out;
}
