#include "webhook.h"

#include <Windows.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <winhttp.h>
#include <filesystem>
#include <conio.h>
#include <gdiplus.h>
#include <thread>
#include <fstream>
#include "../curl/include/curl/curl.h"

#pragma comment(lib, "gdiplus.lib") 
#pragma comment(lib, "winhttp.lib")

#include "../encryption/obfstring.h"

#include "../nlohmann/json.hpp"

using namespace Gdiplus;
using namespace std;

using json = nlohmann::json;

#pragma warning(disable : 4996) 

int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
    UINT num = 0;
    UINT size = 0;

    ImageCodecInfo* pImage = NULL;

    GetImageEncodersSize(&num, &size);
    if (size == 0) return -1;

    pImage = (ImageCodecInfo*)(malloc(size));
    if (pImage == NULL) return -1;

    GetImageEncoders(num, size, pImage);

    for (UINT j = 0; j < num; ++j)
    {
        if (wcscmp(pImage[j].MimeType, format) == 0)
        {
            *pClsid = pImage[j].Clsid;
            free(pImage);
            return j;
        }
    }

    free(pImage);
    return -1;
}

int systemNoOutput(std::string command)
{
    command.insert(0, "/C ");

    SHELLEXECUTEINFOA ShExecInfo = { 0 };
    ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    ShExecInfo.hwnd = NULL;
    ShExecInfo.lpVerb = NULL;
    ShExecInfo.lpFile = "cmd.exe";
    ShExecInfo.lpParameters = command.c_str();
    ShExecInfo.lpDirectory = NULL;
    ShExecInfo.nShow = SW_HIDE;
    ShExecInfo.hInstApp = NULL;

    if (ShellExecuteExA(&ShExecInfo) == FALSE)
        return -1;

    WaitForSingleObject(ShExecInfo.hProcess, INFINITE);

    DWORD rv;
    GetExitCodeProcess(ShExecInfo.hProcess, &rv);
    CloseHandle(ShExecInfo.hProcess);

    return rv;
}

std::string getLicense(std::string path) {
    if (std::filesystem::exists(path)) {
        std::ifstream file(path);
        json data = json::parse(file);

        return data["license"];
    }
    return "NOT_FOUND";
}

size_t ipWriteFunction(void* ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*)ptr, size * nmemb);
    return size * nmemb;
}
