#ifndef UTILITIES_HPP_
#define UTILITIES_HPP_

#include <iostream>
#include <random>
#include <sstream>
#include <string>
#include <cstring>
#include <optional>
#include <Utilities/Extern.hpp>

#define SINGLE_ARG(...) __VA_ARGS__

#define UTF8_INVALID_CHAR 0xFFFD
#define UTF8_MASK_CHAR 0x25CF

#define VOXELVERSE_ASSERT(expr) if (!(expr))\
    crash(formatString("$+:$+: $+: Assertion '$+' failed", __FILE__, __LINE__, __func__, #expr))

/**
 * @brief Structure for environment variables.
 */
struct EnvVars
{
    /**
     * @brief Whether we should dump terrain noise.
     */
    bool dumpTerrainNoise;

    /**
     * @brief Whether we are in dev mode.
     */
    bool devMode;
};

/**
 * @brief The environment.
 */
extern EnvVars envVars;

const int updateDuration = 1000 / 60;

/**
 * @brief Defined in main.cpp.
 */
void endGame();

/**
 * @brief Notify main.cpp about how long it took to render a frame.
 * 
 * @param ms The time.
 */
void notifyFrameTime(double ms);

/**
 * @brief Get the average frame time.
 */
double getAverageFrameTime();

/**
 * @brief Get the average update time.
 */
double getAverageUpdateTime();

/**
 * @brief Get the avergae 'fast update' time.
 */
double getAverageFastUpdateTime();

/**
 * @brief Report a fatal error and crash.
 * 
 * @param message The error message to display.
 */
[[noreturn]] void crash(std::string message);

std::ostream& operator<<(std::ostream &os, glm::vec3 vec);

void formatStream(std::ostream &os, const char *fmt);

template<int N, typename T, glm::qualifier Q>
std::ostream& operator<<(std::ostream &os, const glm::vec<N, T, Q> v)
{
    os << "(";

    int i;
    for (i=0; i<N; i++)
    {
        if (i != 0)
        {
            os << ", ";
        }

        os << v[i];
    }

    os << ")";
    return os;
}

template<typename TCurrentElement, typename... TArgs>
void formatStream(std::ostream &os, const char *fmt, TCurrentElement currentElement, TArgs... args)
{
    const char *marker = std::strchr(fmt, '$');
    if (marker == nullptr)
    {
        formatStream(os, fmt);
        return;
    }

    if (marker != fmt)
    {
        os.write(fmt, marker-fmt);
    }

    switch (marker[1])
    {
    case '$':
        // escaping '$'
        os << '$';
        formatStream(os, marker+2, currentElement, args...);
        break;
    case '*':
        // output current element, don't move forward
        os << currentElement;
        formatStream(os, marker+2, currentElement, args...);
        break;
    case '+':
        // output current element, move forward
        os << currentElement;
        formatStream(os, marker+2, args...);
        break;
    default:
        crash(std::string("formatStream: Invalid format string: ") + fmt);
    }
}

template<typename... TArgs>
std::string formatString(const char *fmt, TArgs... args)
{
    std::stringstream ss;
    formatStream(ss, fmt, args...);
    return ss.str();
}

template<typename TDest, typename TSource>
bool isInstance(TSource &value)
{
    return dynamic_cast<TDest*>(&value) != nullptr;
}

template<typename T>
T& pickRandom(std::vector<T> &choices)
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, choices.size() - 1);
    int randomIndex = dis(gen);
    return choices[randomIndex];
}

/**
 * @brief Ask for a password from standard input.
 */
std::string inputPassword(std::string prompt);

/**
 * @brief Perform bilinear interpolation.
 */
float interpolate2D(float p00, float p10, float p01, float p11, float tx, float ty);

/**
 * @brief Perform bilinear interpolation.
 */
float interpolate2DSmooth(float p00, float p10, float p01, float p11, float tx, float ty);

/**
 * @brief Smooth out a curve in [0, 1].
 */
float smoothstep(float t);

/**
 * @brief Convert a size (in bytes) to a string.
 */
std::string formatDataSize(size_t size);

/**
 * @brief Move the specified path to the trash.
 * 
 * @param path The path to move to the trash.
 * @return `std::nullopt` on success; error message on error.
 */
std::optional<std::string> moveToTrash(std::string path);

/**
 * @brief Returns the path to use for a dump file.
 * 
 * After this function returns, the parent directory will exist.
 * 
 * @param filename The name of the file.
 * @return The resulting path.
 */
std::string getDumpPath(std::string filename);

/**
 * @brief Returns true if stdout points to a console/terminal.
 */
bool isOutputtingToConsole();

/**
 * @brief Zlib-compress a vector of bytes.
 * 
 * @param bytes The data to compress.
 * @param output The output vector; will be cleared, and filled with compressed output.
 * @param level The compression level.
 */
void compressBytes(const std::vector<uint8_t> &bytes, std::vector<uint8_t> &output, int level);

/**
 * @brief Uncompress a vector of zlib-compressed bytes.
 * 
 * @param bytes The zlib-compressed bytes.
 * @param output The output vector; will be cleared, and filled with uncompressed output.
 * @return True if successful, false on error (e.g. invalid data).
 */
bool uncompressBytes(const std::vector<uint8_t> &bytes, std::vector<uint8_t> &output);

/**
 * @brief Read a codepoint from a UTF-8 string.
 * 
 * @param str The UTF-8 string.
 * @param offset Offset (in bytes) into the string; will be moved to the next codepoint.
 * @return The decoded character; UTF8_INVALID_CHAR if there was a decoding error.
 */
uint64_t utf8read(const std::string &str, size_t &offset);

/**
 * @brief Move through a UTF-8 string by the specified number of characters.
 *
 * If you move backwards from offset 0, you stay at offset 0. If you move forwards from the end
 * of the string, you stay at the end of the string. The end of the string is a valid position
 * which can be moved to and from.
 *
 * @param str The UTF-8 string.
 * @param offset Offset (in bytes) into the string; will be moved to the destination codepoint.
 * @param delta Number of characters to move; negative values mean backwards.
 */
void utf8move(const std::string &str, size_t &offset, int delta);

/**
 * @brief Returns the input string, with whitespace removed from either end.
 */
std::string trim(const std::string &str);

/**
 * @brief Check the validity of a potential world name.
 *
 * Returns the empty string if the world name is valid. Otherwise, returns the error message.
 */
std::string getWorldNameError(std::string worldName);

/**
 * @brief Given a random seed, generate a float in the range 0-1 efficiently.
 */
float unormFromBits(uint32_t seed);

/**
 * @brief Return a human-readable string for the specified number of game ticks.
 * 
 * It has the format "00h:00m:00s".
 */
std::string formatTicks(uint64_t ticks);

/**
 * @brief Interpolates a position on a line.
 * 
 * The line contains points `a` and `b`. This function returns another point on the line, such
 * that `result[axis] == knownValue`.
 */
template<typename T>
glm::tvec2<T> interpolateLine(const glm::tvec2<T> &a, const glm::tvec2<T> &b, T knownValue, int axis)
{
    int dependentAxis = axis ^ 1;

    T numerator = (b[dependentAxis] - a[dependentAxis]) * (knownValue - a[axis]);
    T denominator = b[axis] - a[axis];

    glm::tvec2<T> result(0);
    result[axis] = knownValue;
    result[dependentAxis] = a[dependentAxis] + numerator / denominator;

    return result;
}

/**
 * @brief Evaluate `y` for the given `x`, as an exponential function that crosses through the control points.
 */
float expWithControlPoints(float x, glm::vec2 controlA, glm::vec2 controlB);

/**
 * @brief Returns a random value 0..1.
 */
float randomUnit();

/**
 * @brief Returns a random value -1..1.
 */
float randomSignedUnit();

#endif