/*
  Malcolm Kesson
  Nov 11 2019 
    in the typedef struct {
        std::string archivesPathPattern;
        ....
        ...
        } STRUCT_NAME;
        
    in the ConvertParameters() function,
        
        std::string  rib_dir_glob_pattern("/Users/jdoe/Documents/maya/projects/755/arhives/*.rib");
        STRUCT_NAME->archivesPathPattern = rib_dir_glob_pattern;
  
    in the Subdivide() function,
        std::string archivesPathPattern = ((ParamData*)paramsPtr)->archivesPathPattern;
        std::vector <std::string> paths = getFiles(archivesPathPattern);
        in the loop
            std::random_shuffle( paths.begin(), paths.end() );
            RiReadArchiveV(paths[0].c_str(), NULL, 0, NULL, NULL );
            
*/
#include <vector>
#include <string>
#include <stdio.h>
  
#ifdef  _WIN32
    #include <Windows.h>
    std::vector<std::string> winGetFiles(std::string pattern) {
        std::vector<std::string> paths;
        std::string parentDir = pattern.substr(0, pattern.find_last_of("/\\"));
        //printf("%s\n", parentDir.c_str());
        WIN32_FIND_DATA fd;
        HANDLE hFind = ::FindFirstFile(pattern.c_str(), &fd);
        if(hFind != INVALID_HANDLE_VALUE) {
            do {
                // read all (real) files in current folder
                // , delete '!' read other 2 default folder . and ..
                if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                    paths.push_back(parentDir + "/" + fd.cFileName);
                }
            } while(::FindNextFile(hFind, &fd));
            ::FindClose(hFind);
        }
        return paths;
    }
#else
    #include <glob.h>
    std::vector<std::string> globGetFiles(const std::string& pattern){
        glob_t glob_result;
        glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result);
        std::vector<std::string> paths;
        for(unsigned int i=0;i<glob_result.gl_pathc;++i){
            paths.push_back(std::string(glob_result.gl_pathv[i]));
            }
        globfree(&glob_result);
        return paths;
        }
#endif
  
std::vector<std::string> getFiles(std::string pattern) {
    #ifdef  _WIN32
        return winGetFiles(pattern);
    #else
        return globGetFiles(pattern);
    #endif
    }
  
// Here for testing purposes. It will be ignored when a procprim calls getFiles().
int main() {
    std::vector<std::string> files = getFiles("/Users/malcolmkesson/Documents/maya/projects/22/renderman/rib/riftest/v001_t01/*.rib");
//    std::vector<std::string> files = getFiles("H:/maya/projects/22/renderman/rib/first/v001_t01/*.rib");
    for(unsigned int n = 0; n < files.size(); n++) {
        printf("%s \n", files[n].c_str());
        }
  
    }