/** Reads a challenge from the given filename. The challenge will then either
 *  be stored, or (if the challenge version is not supported anymore
 *  \param filename Name of the challenge file to read.
 */
void UnlockManager::addChallenge(const std::string& filename)
{
    ChallengeData* new_challenge = NULL;
    try
    {
        new_challenge = new ChallengeData(filename);
        new_challenge->check();
    }
    catch (std::runtime_error& ex)
    {
        std::cerr << "\n/!\\ An error occurred while loading challenge file '" << filename << "' : "
                  << ex.what() << " : challenge will be ignored.\n\n"; 
        if (new_challenge != NULL) delete new_challenge;
        return;
    }
    addOrFreeChallenge(new_challenge);
    
}   // addChallenge
/** Reads a challenge from the given filename. The challenge will then either
 *  be stored, or (if the challenge version is not supported anymore
 *  \param filename Name of the challenge file to read.
 */
void UnlockManager::addChallenge(const std::string& filename)
{
    ChallengeData* new_challenge = NULL;
    try
    {
        new_challenge = new ChallengeData(filename);
        new_challenge->check();
    }
    catch (std::runtime_error& ex)
    {
        Log::warn("unlock_manager", "An error occurred while loading "
                   "challenge file '%s' : %s challenge will be ignored.",
                   filename.c_str(), ex.what());
        if (new_challenge) delete new_challenge;
        return;
    }
    addOrFreeChallenge(new_challenge);

}   // addChallenge
void UnlockManager::readAllChallengesInDirs(const std::vector<std::string>* all_dirs)
{
    for(std::vector<std::string>::const_iterator dir = all_dirs->begin();
        dir != all_dirs->end(); dir++)
    {
        std::set<std::string> all_files;
        file_manager->listFiles(all_files, *dir);

        for(std::set<std::string>::iterator file = all_files.begin();
            file != all_files.end(); file++)
        {
            if (!StringUtils::hasSuffix(*file,".challenge")) continue;

            std::string filename = *dir + "/" + *file;

            FILE* f = fopen(filename.c_str(), "r");
            if (f)
            {
                fclose(f);
                ChallengeData* new_challenge = NULL;
                try
                {
                    new_challenge = new ChallengeData(filename);
                }
                catch (std::runtime_error& ex)
                {
                    Log::warn("unlock_manager", "An error occurred while "
                              "loading challenge file '%s' : %s.\n"
                              "Challenge will be ignored.",
                              filename.c_str(), ex.what());
                    continue;
                }
                addOrFreeChallenge(new_challenge);
            }   // if file

        }   // for file in files
    }   // for dir in all_track_dirs
}