/*
 * File: soundbankBundleInfo.cpp
 *
 * Author: Jordan Rivas
 * Created: 04/24/17
 *
 *  Description: Struct defines soundbank bundle information provided in SoundbankBundleInfo.json file. This file is
 *               generated by build server script and is delivered to app with audio assets. Use this information to
 *               locate and load soundbanks.
 *
 * Copyright: Anki, Inc. 2017
 */


#include "audioEngine/soundbankBundleInfo.h"
#include "json/json.h"
#include "util/logging/logging.h"
#include "util/fileUtils/fileUtils.h"
#include "util/string/stringUtils.h"


namespace Anki {
namespace AudioEngine {
  
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SoundbankBundleInfo::SoundbankBundleInfo( const Json::Value& jsonData )
{
  // Json bundle keys
  static const char* BUNDLE_NAME_KEY = "bundle_name";
  static const char* SOUNDBANK_NAME_KEY = "soundbank_name";
  static const char* LANG_KEY = "language";
  static const char* PATH_KEY = "path";
  static const char* TYPE_KEY = "type";
  
  // Set values from json data
  BundleName = jsonData[BUNDLE_NAME_KEY].asString();
  SoundbankName = jsonData[SOUNDBANK_NAME_KEY].asString();
  Language = jsonData[LANG_KEY].asString();
  Path = jsonData[PATH_KEY].asString();
  // Optional value
  if ( jsonData.isMember(TYPE_KEY) ) {
    auto typeValStr = jsonData[TYPE_KEY].asString();
    if ( Anki::Util::StringCaseInsensitiveEquals( typeValStr, "lazy" ) ) {
      Type = SoundbankBundleInfo::BankType::LazyLoad;
    }
    else if ( Anki::Util::StringCaseInsensitiveEquals( typeValStr, "debug" ) ) {
      Type = SoundbankBundleInfo::BankType::Debug;
    }
  }
}
 
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool SoundbankBundleInfo::GetSoundbankBundleInfoMetadata( const std::string& filePath,
                                                          std::vector<SoundbankBundleInfo>& out_list )
{
  out_list.clear();
  const std::string jsonStr = Anki::Util::StringFromContentsOfFile( filePath );
  if ( jsonStr.empty() ) {
    PRINT_NAMED_WARNING("SoundbankBundleInfo.GetSoundbankBundleInfoMetadata",
                        "Could NOT read contents of '%s'", filePath.c_str());
    return false;
  }
  
  Json::Value root;
  Json::Reader reader;
  bool parsingSuccessful = reader.parse( jsonStr, root );
  if ( parsingSuccessful && root.isArray() ) {
    for ( const auto& aBundleInfoObj : root ) {
      out_list.push_back( SoundbankBundleInfo( aBundleInfoObj ) );
    }
  }
  else {
    PRINT_NAMED_WARNING("SoundbankBundleInfo.GetSoundbankBundleInfoMetadata",
                        "'%s' is NOT a JSON Array", filePath.c_str());
    return false;
  }
  
  return true;
}

} // AudioEngine
} // Anki
