
#include <stdint.h>
#include <vector>
#include <wchar.h>
#include <cstring>
#include <ctime>
#include <chrono>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <codecvt>
#include <unordered_map>
#include <format>

// #include <openssl/evp.h>
// #include <openssl/aes.h>
#include <openssl/conf.h>
#include <openssl/err.h> /* errors */
#include <openssl/ssl.h> /* core library */
// #include <openssl/sha.h>

#include "utils.h"

using namespace std;

const std::string base64_chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

const char base64_url_alphabet[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'};

void TestFunction(int i)
{
  std::cout << i << "\n";
  std::cout << i + 1 << "\n";
}

void generatePause()
{
  cin.get();
  // system("pause");
}

string getXmlContentFromString(string source, string xmlTag)
{
  int xmlTagSize = xmlTag.length();
  int keyIndexStart = source.find("<" + xmlTag + ">");
  int keyIndexEnd = source.find("</" + xmlTag + ">");
  std::string keyContentString = source.substr(keyIndexStart + xmlTagSize + 2, (keyIndexEnd - keyIndexStart - xmlTagSize - 2));
  return keyContentString;
}

string getString(unsigned char *charArray)
{
  std::string fileContent(reinterpret_cast<char *>(charArray), sizeof(charArray));
  return fileContent;
}

void getCharsFromString1(string source, char *charArray)
{
  memset(charArray, 0, sizeof(charArray));
  int length = source.length(); // Length of the string (excluding null character)
  // charArray[length]; // Character array to store the string
  for (int i = 0; i < length; i++)
  {
    charArray[i] = source[i];
  }
}

void getCharsFromString(string &source, char *charArray, int length)
{
  memset(charArray, 0, length);
  for (int i = 0; i < length; i++)
  {
    charArray[i] = source[i];
  }
}

void getCharsFromString(string source, char *charArray)
{
  memset(charArray, 0, sizeof(charArray));
  int length = source.length(); // Length of the string (excluding null character)
  // charArray[length]; // Character array to store the string
  for (int i = 0; i < length; i++)
  {
    charArray[i] = source[i];
  }
}

float byteArrayToFloat(const BYTE *byteArray)
{
  // Ensure that the byte array has at least 4 elements (32 bits)
  if (byteArray == NULL)
  {
    // Handle error: The pointer is NULL
    return 0.0f; // or any appropriate error handling
  }

  int sizeArray = sizeof(byteArray);

  // Interpret the byte array as a 32-bit floating-point value
  uint32_t intValue = 0;
  if (sizeArray > 0)
    intValue |= ((uint32_t)byteArray[0] << 24);
  if (sizeArray > 1)
    intValue |= ((uint32_t)byteArray[1] << 16);
  if (sizeArray > 2)
    intValue |= ((uint32_t)byteArray[2] << 8);
  if (sizeArray > 0)
    intValue |= byteArray[3];

  // Typecast the integer representation to a float
  float floatValue;
  memcpy(&floatValue, &intValue, sizeof(float));

  return floatValue;
}

std::string right(const std::string &sourceString, size_t numChars)
{
  if (numChars >= sourceString.size())
  {
    return sourceString; // If numChars is greater or equal to the string size, return the whole string.
  }
  return sourceString.substr(sourceString.size() - numChars);
}

std::tm dt_to_date(const std::chrono::system_clock::time_point &tp)
{
  std::time_t time = std::chrono::system_clock::to_time_t(tp);
  return *std::localtime(&time);
}

std::string parseCID(const std::string &cidHex)
{
  // Convert hexadecimal string to binary string
  std::string cidBinary;
  for (char c : cidHex)
  {
    std::string binary = "0000";
    int val;
    if (c >= '0' && c <= '9')
    {
      val = c - '0';
    }
    else if (c >= 'a' && c <= 'f')
    {
      val = c - 'a' + 10;
    }
    else if (c >= 'A' && c <= 'F')
    {
      val = c - 'A' + 10;
    }
    else
    {
      continue; // Ignore non-hex characters
    }
    for (int i = 3; i >= 0; --i)
    {
      binary[i] = '0' + (val & 1);
      val >>= 1;
    }
    cidBinary += binary;
  }

  // Define the length of individual fields in the CID
  const int lengths[] = {8, 16, 40, 8, 32, 12, 7, 4};
  const char *fields[] = {"MID", "OID", "PNM", "PRV", "PSN", "MDT", "CRC", "unused"};

  // Parse the binary string and print individual fields
  int pos = 0;
  for (int i = 0; i < 8; ++i)
  {
    std::string fieldData = cidBinary.substr(pos, lengths[i]);
    std::cout << fields[i] << ": " << fieldData << std::endl;
    pos += lengths[i];
  }

  return cidBinary; // Optionally, you can return the full binary string
}

void bitsToCharArray(const std::string &bitsStr, char *charArray)
{
  int bitsLen = bitsStr.length();
  int charArraySize = bitsLen / 8; // Assuming bitsStr.length() is a multiple of 8

  for (int i = 0; i < charArraySize; i++)
  {
    std::string byteStr = bitsStr.substr(i * 8, 8);
    charArray[i] = std::bitset<8>(byteStr).to_ulong();
  }
}

uint16_t calculateCRC16(const uint8_t *data, size_t length)
{
  const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
  uint16_t crc = 0xFFFF;              // Initial value

  for (size_t i = 0; i < length; i++)
  {
    crc ^= data[i]; // XOR with the current data byte

    for (int j = 0; j < 8; j++)
    {
      if (crc & 0x0001)
      {
        crc = (crc >> 1) ^ polynomial;
      }
      else
      {
        crc = crc >> 1;
      }
    }
  }

  return crc;
}

uint16_t crc16(const unsigned char *data_p, unsigned char length)
{
  uint16_t x;
  uint16_t crc = 0xFFFF;

  while (length--)
  {
    x = crc >> 8 ^ *data_p++;
    x ^= x >> 4;
    crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x << 5)) ^ ((unsigned short)x);
  }
  return crc;
}

void wordToByteArray(uint16_t wordValue, uint8_t byteArray[2])
{
  byteArray[0] = static_cast<uint8_t>(wordValue & 0xFF);        // Low byte
  byteArray[1] = static_cast<uint8_t>((wordValue >> 8) & 0xFF); // High byte
}

uint16_t calculateCrc(const uint8_t *data, size_t length)
{
  uint16_t crc = 0xFFFF;
  uint16_t makeData = 0;

  uint16_t cCrcTable[] = {0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
                          0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
                          0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
                          0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
                          0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
                          0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
                          0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
                          0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
                          0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
                          0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
                          0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
                          0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
                          0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
                          0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
                          0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
                          0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
                          0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
                          0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
                          0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
                          0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
                          0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
                          0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
                          0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
                          0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
                          0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
                          0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
                          0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
                          0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
                          0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
                          0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
                          0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
                          0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040};

  uint8_t byteArray[2];

  for (int i = 0; i < length; i++)
  {
    // wordToByteArray(crc, byteArray);
    makeData = data[i] ^ (crc);
    crc = crc >> 8;
    crc = crc ^ cCrcTable[i];
    data = data + 1;
  }

  /* orig
  crc := 16#FFFF;

FOR i := 0 TO dataLen - 1 DO
  makeData := data^ XOR WORD_TO_BYTE( crc );
  crc := SHR( crc, 8 );
  crc := crc XOR cCrcTable[makeData];
  data := data + 1;
END_FOR;

fEz_crc16 := crc;
  */

  return crc;
}

void showCurrentTime()
{
  std::time_t now = std::time(nullptr);
  std::cout << "Current time (ctime): " << std::ctime(&now);

  // Using chrono to get the current time
  auto currentTime = std::chrono::system_clock::now();
  std::time_t currentTimeT = std::chrono::system_clock::to_time_t(currentTime);
  std::cout << "Current time (chrono): " << std::ctime(&currentTimeT);
}

WORD getCurrentDateAsCODESYSDate()
{
  /*
  Bits 0-4: Day (1 to 31)
Bits 5-8: Month (1 to 12)
Bits 9-15: Year (0 to 127, where 0 represents the year 1984)

date: 2023-07-21 = 0x0A17 ?

daatum: 060: 80 F9 C6 64

  */
  std::time_t currentTime = std::time(nullptr);
  std::tm *currentTm = std::localtime(&currentTime);

  int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
  int month = currentTm->tm_mon + 1;    // tm_mon represents months from 0 to 11
  int day = currentTm->tm_mday;

  uint16_t codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);

  return codesysDate;
}

DWORD getCurrentDateAsCODESYSDateDword()
{
  std::time_t currentTime = std::time(nullptr);
  std::tm *currentTm = std::localtime(&currentTime);

  int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
  int month = currentTm->tm_mon + 1;    // tm_mon represents months from 0 to 11
  int day = currentTm->tm_mday;

  DWORD codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);

  return codesysDate;
}

uint16_t convertToCODESYSDate(int day, int month, int year)
{
  return (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
}

uint16_t convertToCODESYSTime(int hour, int minute)
{
  return (static_cast<uint16_t>(hour) << 11) | (static_cast<uint16_t>(minute) << 5);
}

DateAndTime getCurrentDateTimeAsCODESYSDateTime()
{
  std::time_t currentTime = std::time(nullptr);
  std::tm *currentTm = std::localtime(&currentTime);

  int year = currentTm->tm_year + 1900; // tm_year represents years since 1900
  int month = currentTm->tm_mon + 1;    // tm_mon represents months from 0 to 11
  int day = currentTm->tm_mday;
  int hour = currentTm->tm_hour;
  int minute = currentTm->tm_min;
  int second = currentTm->tm_sec;

  uint16_t codesysDate = (static_cast<uint16_t>(year - 1984) << 9) | (static_cast<uint16_t>(month) << 5) | static_cast<uint16_t>(day);
  uint16_t codesysTime = (static_cast<uint16_t>(hour) << 11) | (static_cast<uint16_t>(minute) << 5) | (static_cast<uint16_t>(second) >> 1);

  DateAndTime codesysDateTime = {codesysDate, codesysTime};
  return codesysDateTime;
}

DATE getLicDate()
{
  time_t ttime = time(0);
  tm *local_time = localtime(&ttime);
  int hoursSeconds = 3600 * local_time->tm_hour;
  int minutesSeconds = 60 * local_time->tm_min;
  int seconds = 1 * local_time->tm_sec;
  int totalSeconds = hoursSeconds + minutesSeconds + seconds;

#ifdef WINDOWS
  DATE dateOnly = ttime - totalSeconds + 7200; // (pro windows); // 7200 + vteřina za dvě hodiny pro srování
#else
  DATE dateOnly = ttime - totalSeconds;
#endif

  return dateOnly;
}

string getDate()
{
  auto r = std::chrono::system_clock::now();
  auto rp = std::chrono::system_clock::to_time_t(r);
  std::string h(ctime(&rp)); // converting to c++ string
  return h;
}

std::vector<unsigned char> aes256_cbc_encrypt(const std::vector<unsigned char> &plaintext, const std::vector<unsigned char> &key, const std::vector<unsigned char> &iv)
{
  std::vector<unsigned char> ciphertext;
  EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();

  EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.data(), iv.data());

  int ciphertext_len;
  int len;
  int max_chunk_size = EVP_CIPHER_block_size(EVP_aes_256_cbc());

  ciphertext.resize(plaintext.size() + max_chunk_size);

  EVP_EncryptUpdate(ctx, ciphertext.data(), &len, plaintext.data(), plaintext.size());
  ciphertext_len = len;

  EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len);
  ciphertext_len += len;

  EVP_CIPHER_CTX_free(ctx);

  ciphertext.resize(ciphertext_len);
  return ciphertext;
}

void handleErrors(void)
{
  ERR_print_errors_fp(stderr);
  abort();
}

int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *key,
            unsigned char *iv, unsigned char *ciphertext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int ciphertext_len;

  /* Create and initialise the context */
  if (!(ctx = EVP_CIPHER_CTX_new()))
    handleErrors();

  /*
   * Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits
   */
  if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    handleErrors();

  /*
   * Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */
  if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    handleErrors();
  ciphertext_len = len;

  /*
   * Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */
  if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
    handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}

int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
            unsigned char *iv, unsigned char *plaintext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int plaintext_len;

  /* Create and initialise the context */
  if (!(ctx = EVP_CIPHER_CTX_new()))
    handleErrors();

  /*
   * Initialise the decryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits
   */
  if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    handleErrors();

  /*
   * Provide the message to be decrypted, and obtain the plaintext output.
   * EVP_DecryptUpdate can be called multiple times if necessary.
   */
  if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
    handleErrors();
  plaintext_len = len;

  /*
   * Finalise the decryption. Further plaintext bytes may be written at
   * this stage.
   */
  if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
    handleErrors();
  plaintext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return plaintext_len;
}

bool CompareFiles(const char *fileName, const char *fileName1)
{

  FILE *fp1;
  FILE *fp2;

  fp1 = fopen(fileName, "rb"); // read mode
  fseek(fp1, 0, SEEK_END);     // seek to end of file
  int size1 = ftell(fp1);      // get current file pointer
  fseek(fp1, 0, SEEK_SET);

  fp2 = fopen(fileName1, "rb"); // read mode
  fseek(fp2, 0, SEEK_END);      // seek to end of file
  int size2 = ftell(fp2);       // get current file pointer
  fseek(fp2, 0, SEEK_SET);

  if (fp1 == NULL || fp2 == NULL)
  {
    while (1)
    {
      int byte1 = fgetc(fp1);
      int byte2 = fgetc(fp2);

      if (byte1 == EOF || byte2 == EOF)
      {
        if (byte1 != byte2)
        {
          return false; // 1 indicates files are different
        }
        break;
      }

      if (byte1 != byte2)
      {
        return false; // 1 indicates files are different
        break;
      }
    }
  }
  else
    return false;

  fclose(fp1);
  fclose(fp2);

  return true;
}

// converts character array
// to string and returns it
string convertToString(char *a, int size)
{
  int i;
  string s = "";
  for (i = 0; i < size; i++)
  {
    s = s + a[i];
  }
  return s;
}

std::string base64_decode(const std::string &in)
{
  std::string out;
  std::vector<int> T(256, -1);
  unsigned int i;
  for (i = 0; i < 64; i++)
    T[base64_url_alphabet[i]] = i;

  int val = 0, valb = -8;
  for (i = 0; i < in.length(); i++)
  {
    unsigned char c = in[i];
    if (T[c] == -1)
      break;
    val = (val << 6) + T[c];
    valb += 6;
    if (valb >= 0)
    {
      out.push_back(char((val >> valb) & 0xFF));
      valb -= 8;
    }
  }
  return out;
}

void processCharArray(const unsigned char *arr)
{
  size_t arraySize = sizeof(arr) / sizeof(arr[0]);
  for (size_t i = 0; i < arraySize; ++i)
  {
    std::cout << arr[i] << " ";
  }
  std::cout << std::endl;
}

std::string base64_encode(const std::string &in)
{
  std::string out;
  int val = 0, valb = -6;
  size_t len = in.length();
  unsigned int i = 0;
  for (i = 0; i < len; i++)
  {
    unsigned char c = in[i];
    val = (val << 8) + c;
    valb += 8;
    while (valb >= 0)
    {
      out.push_back(base64_url_alphabet[(val >> valb) & 0x3F]);
      valb -= 6;
    }
  }
  if (valb > -6)
  {
    out.push_back(base64_url_alphabet[((val << 8) >> (valb + 8)) & 0x3F]);
  }
  return out;
}

std::string base64_encode_array(const unsigned char *source)
{
  size_t arraySize = sizeof(source) / sizeof(source[0]);
  std::string out;
  int val = 0, valb = -6;
  unsigned int i = 0;
  for (i = 0; i < arraySize; i++)
  {
    unsigned char c = source[i];
    val = (val << 8) + c;
    valb += 8;
    while (valb >= 0)
    {
      out.push_back(base64_url_alphabet[(val >> valb) & 0x3F]);
      valb -= 6;
    }
  }
  if (valb > -6)
  {
    out.push_back(base64_url_alphabet[((val << 8) >> (valb + 8)) & 0x3F]);
  }
  return out;
}

std::string base64_decode_ai(const std::string &encoded)
{
  std::string decoded;
  int val = 0, valb = -8;

  for (char c : encoded)
  {
    if (base64_chars.find(c) == std::string::npos)
      break;

    val = (val << 6) + base64_chars.find(c);
    valb += 6;

    if (valb >= 0)
    {
      decoded.push_back(static_cast<unsigned char>((val >> valb) & 0xFF));
      valb -= 8;
    }
  }

  return decoded;
}

std::string base64_encode_ai(const std::string &input)
{
  std::string encoded;

  size_t input_length = input.length();
  size_t i = 0;

  while (i < input_length)
  {
    unsigned char input_chunk[3] = {0};
    size_t chunk_size = 0;

    // Fill the input chunk with up to 3 bytes from the input string
    for (size_t j = 0; j < 3; ++j)
    {
      if (i < input_length)
      {
        input_chunk[j] = input[i++];
        ++chunk_size;
      }
    }

    // Encode the input chunk into 4 Base64 characters
    encoded += base64_chars[(input_chunk[0] & 0xFC) >> 2];
    encoded += base64_chars[((input_chunk[0] & 0x03) << 4) |
                            ((input_chunk[1] & 0xF0) >> 4)];
    encoded += (chunk_size > 1)
                   ? base64_chars[((input_chunk[1] & 0x0F) << 2) |
                                  ((input_chunk[2] & 0xC0) >> 6)]
                   : '=';
    encoded += (chunk_size > 2)
                   ? base64_chars[input_chunk[2] & 0x3F]
                   : '=';
  }

  return encoded;
}

unordered_map<string, string> getArguments(int argc, char *argv[])
{
  const char splitChar = '=';
  unordered_map<string, string> result;
  if (argc <= 1)
    return result;

  for (int i = 1; i < argc; ++i)
  {
    bool isArgName = true;
    int argLength = strlen(argv[i]);
    string argName;
    string argValue;

    for (int j = 0; j < argLength; j++)
    {
      if (argv[i][j] == splitChar)
      {
        isArgName = false;
        continue;
      }

      if (isArgName)
      {
        argName += argv[i][j];
      }
      else
      {
        argValue += argv[i][j];
      }
    }

    result.insert(make_pair(argName, argValue));
  }
  return result;
}

unordered_map<string, const char *> mapArguments(int argc, char *argv[])
{
  const char splitChar = '=';
  unordered_map<string, const char *> result;
  if (argc <= 1)
    return result;

  for (int i = 1; i < argc; ++i)
  {
    bool isArgName = true;
    int argLength = strlen(argv[i]);
    string argName;
    string argValue;
    char *argValueChar;

    for (int j = 0; j < argLength; j++)
    {
      if (argv[i][j] == splitChar)
      {
        isArgName = false;
        continue;
      }

      if (isArgName)
      {
        argName += argv[i][j];
      }
      else
      {
        argValue += argv[i][j];
      }
    }

    const char *chValue = argValue.c_str();

    result.insert(make_pair(argName, chValue));
  }
  return result;
}

string getCompletePath(string fileName)
{
#ifdef WINDOWS
  return fileName;
#else
  std::filesystem::path exePath = std::filesystem::canonical("/proc/self/exe"); // / std::filesystem::path(argv[0]));
  std::filesystem::path fullPathOther = exePath.parent_path() / fileName;
  std::string fullPathStrOther = fullPathOther.string();
  return fullPathStrOther;
#endif
}

char *getFileContent(string fileName)
{
  FILE *file;
  char ch;
  long lSize;
  size_t result;

  const int fileNameLength = fileName.length();
  char fileNameCh[fileNameLength] = {};
  for (int i = 0; i < fileName.length(); i++)
    fileNameCh[i] = fileName[i];

  file = fopen(fileNameCh, "rb"); // read mode
  fseek(file, 0, SEEK_END);       // seek to end of file
  const int size = ftell(file);   // get current file pointer
  fseek(file, 0, SEEK_SET);

  if (file == NULL)
  {
    perror("Error while opening the file.\n");
    return nullptr;
  }

  char licenceContent[size];

  for (int i = 0; i < size; i++)
  {
    ch = fgetc(file);
    licenceContent[i] = ch;
  }

  fclose(file);

  return licenceContent;
}

void appendStringToVector(const std::string &str, std::vector<unsigned char> &charVector)
{
  // Get the length of the string
  size_t strLength = str.length();

  // Append each character of the string to the vector
  for (size_t i = 0; i < strLength; ++i)
  {
    charVector.push_back(static_cast<unsigned char>(str[i]));
  }
}

void coutVector(std::vector<unsigned char> &charVector)
{
  for (const auto &elem : charVector)
  {
    std::cout << elem;
  }
}

uint16_t calculateCRC16(std::vector<unsigned char> &charVector)
{
  const uint16_t polynomial = 0xA001; // CRC16-CCITT polynomial
  uint16_t crc = 0xFFFF;              // Initial value

  size_t length = charVector.size();

  for (size_t i = 0; i < length; i++)
  {
    crc ^= charVector[i]; // XOR with the current data byte

    for (int j = 0; j < 8; j++)
    {
      if (crc & 0x0001)
      {
        crc = (crc >> 1) ^ polynomial;
      }
      else
      {
        crc = crc >> 1;
      }
    }
  }

  return crc;
}

uint32_t bytesToDword(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
{
  return static_cast<uint32_t>(byte1) |
         (static_cast<uint32_t>(byte2) << 8) |
         (static_cast<uint32_t>(byte3) << 16) |
         (static_cast<uint32_t>(byte4) << 24);
}

uint32_t bytesToWord(uint8_t byte1, uint8_t byte2)
{
  return static_cast<uint32_t>(byte1) | (static_cast<uint32_t>(byte2) << 8);
}

std::vector<unsigned char> joinVectors(const std::vector<unsigned char> &vector1, const std::vector<unsigned char> &vector2)
{
  std::vector<unsigned char> result;
  result.insert(result.end(), vector1.begin(), vector1.end());
  result.insert(result.end(), vector2.begin(), vector2.end());
  return result;
}

string readFileToString(const std::string &filename, std::size_t sizeS)
{

  std::ifstream file(filename, std::ios::binary);

  if (!file.is_open())
  {
    std::cerr << "Error: Could not open file '" << filename << "'" << std::endl;
    return ""; // Return an empty string to indicate an error
  }

  // Read the file into a stringstream
  std::stringstream buffer;
  buffer << file.rdbuf();

  // Get the content of the stringstream as a string
  std::string fileContent = buffer.str();

  // Ensure the string has at most sizeS characters
  if (fileContent.size() > sizeS)
  {
    fileContent.resize(sizeS);
  }

  return fileContent;
}

bool readFile(string fileName, vector<char> &output)
{
  std::ifstream file(fileName, std::ios::in | std::ios::binary);

  if (!file.is_open())
  {
    return false;
  }

  char byte;
  while (file.get(byte))
  {
    // Convert the char to unsigned char and push it into the vector
    output.push_back(byte);
  }


// Get the size of the file
    // file.seekg(0, std::ios::end);
    // streampos fileSize = file.tellg();
    // file.seekg(0, std::ios::beg);

  // Read the file into the buffer
    // if (!file.read(reinterpret_cast<char *>(content.data()), fileSize))
    // {
    //   throw LicenceException((int)GeneralError::FileReadError, "Chyba otevření souboru.");
    // }

  return true;
}
