/*!
 * strings_helpers.cpp
 *
 * Copyright (c) 2015-2018, NADAL Jean-Baptiste. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 * 
 * @Author:  NADAL Jean-Baptiste
 * @Date: 28/06/2015
 *
 */

/*-------------------------------- INCLUDES ---------------------------------*/

#include <cstdarg>
#include <locale>
#include <algorithm>

#include "strings.h"

typedef std::string::value_type char_t;

/*!  ----------------------------------------------------------------------------
 *  @fn SpeachCommand
 *
 *  @brief Constructor of the UBus Speach Command execution.
 */
char_t up_char(char_t ch)
{
    return std::use_facet<std::ctype<char_t>>(std::locale()).toupper(ch);
}

/*!  ----------------------------------------------------------------------------
 *  @fn toupper
 *
 *  @brief method to make a toupper missing commands on the std::string.
 */
std::string toupper(const std::string &src)
{
    //std::string result;
    //std::transform (src.begin(), src.end(), std::back_inserter (result), up_char);
    //return result;
    return src;
}

std::string string_vsprintf(const char *format, std::va_list args)
{
    va_list tmp_args;        //unfortunately you cannot consume a va_list twice
    va_copy(tmp_args, args); //so we have to copy it
    const int required_len = vsnprintf(nullptr, 0, format, tmp_args) + 1;
    va_end(tmp_args);

    std::string buf(required_len, '\0');
    if (std::vsnprintf(&buf[0], buf.size(), format, args) < 0)
    {
        throw std::runtime_error{"string_vsprintf encoding error"};
    }
    return buf;
}

std::string string_sprintf(const char *format, ...) __attribute__((format(printf, 1, 2)));

std::string string_sprintf(const char *format, ...)
{
    std::va_list args;
    va_start(args, format);
    std::string str{string_vsprintf(format, args)};
    va_end(args);
    return str;
}