#include <windows.h>
#include <tlhelp32.h>
#include <vector>
#include <string>

#define ID_START_BUTTON 1
#define ID_STATUS_TEXT 2  // ID for the static text control

// Function prototypes
DWORD_PTR GetAffinityMaskForAllCoresExceptCore0();
bool CheckForRunningProcesses(const std::vector<std::wstring>& processNames);
void CheckAndModifyProcesses(const std::vector<std::wstring>& processNames, HWND hwnd);  // Pass hwnd here
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void OnStartButtonClick(HWND hwnd);
void UpdateStatusText(HWND hwnd, const std::wstring& status);

// Main entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // Remove console window
    FreeConsole();

    std::vector<std::wstring> processNames = {
        L"MuMuPlayer.exe",
        L"MuMuVMMHeadless.exe",
        L"Ld9BoxHeadless.exe",
        L"Ld9BoxSVC.exe",
        L"dnplayer.exe",
        L"HD-Player.exe"
    };

    // Step: Check for running processes before creating the window
    if (!CheckForRunningProcesses(processNames)) {
        MessageBox(NULL, "No emulator found.", "Error", MB_ICONERROR);
        return 0; // Exit the application if no emulators are found
    }

    const char CLASS_NAME[]  = "EmulatorOptimizer";

    // Register the window class
    WNDCLASS wc = {};
    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        "Emulator Optimizer", // Changed title to "Emulator Optimizer"
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 300, 200,
        NULL,
        NULL,
        hInstance,
        NULL);

    if (hwnd == NULL) {
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);

    // Create the Apply Emulator Optimization button
    CreateWindow(
        "BUTTON",  // Predefined class; Unicode assumed 
        "Apply Emulator Optimization", // Button text
        WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles 
        50,         // x position 
        50,         // y position 
        200,        // Button width
        30,         // Button height
        hwnd,       // Parent window
        (HMENU)ID_START_BUTTON,       // Control identifier 
        (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
        NULL);      // Pointer not needed 

    // Create the static text control for status message
    CreateWindow(
        "STATIC",   // Predefined class
        "",         // No initial text
        WS_VISIBLE | WS_CHILD,  // Styles
        50,         // x position
        100,        // y position
        200,        // Width
        30,         // Height
        hwnd,       // Parent window
        (HMENU)ID_STATUS_TEXT,    // Control identifier
        hInstance,
        NULL);

    // Message loop
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

// Windows Procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_COMMAND: {
        if (LOWORD(wParam) == ID_START_BUTTON) {
            OnStartButtonClick(hwnd);
        }
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;

    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

// Function to calculate affinity mask for all cores except core 0
DWORD_PTR GetAffinityMaskForAllCoresExceptCore0() {
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    DWORD_PTR mask = 0;

    // Set bits for all cores except core 0
    for (DWORD i = 1; i < sysInfo.dwNumberOfProcessors; i++) {
        mask |= (1ULL << i);
    }

    return mask;
}

// Function to check if any of the specified processes are running
bool CheckForRunningProcesses(const std::vector<std::wstring>& processNames) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        return false;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    bool found = false;

    if (Process32First(hSnapshot, &pe32)) {
        do {
            std::wstring exeFileName(pe32.szExeFile, pe32.szExeFile + strlen(pe32.szExeFile));
            for (const auto& processName : processNames) {
                if (exeFileName == processName) {
                    found = true;
                    break;
                }
            }
            if (found) break;
        } while (Process32Next(hSnapshot, &pe32));
    }

    CloseHandle(hSnapshot);
    return found;
}

// Function to monitor and modify specific processes
void CheckAndModifyProcesses(const std::vector<std::wstring>& processNames, HWND hwnd) {
    DWORD_PTR affinityMask = GetAffinityMaskForAllCoresExceptCore0();
    bool optimized = false; // Flag to check if optimization was successful

    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        MessageBox(NULL, "Failed to create process snapshot.", "Error", MB_ICONERROR);
        return;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (Process32First(hSnapshot, &pe32)) {
        do {
            std::wstring exeFileName(pe32.szExeFile, pe32.szExeFile + strlen(pe32.szExeFile));

            for (const auto& processName : processNames) {
                if (exeFileName == processName) {
                    HANDLE hProcess = OpenProcess(PROCESS_SET_INFORMATION, FALSE, pe32.th32ProcessID);
                    if (hProcess) {
                        if (SetProcessAffinityMask(hProcess, affinityMask)) {
                            optimized = true; // Set flag if at least one process optimization was successful
                        }
                        CloseHandle(hProcess);
                    }
                }
            }
        } while (Process32Next(hSnapshot, &pe32));
    }

    CloseHandle(hSnapshot);

    // Update the status text if any process was optimized
    if (optimized) {
        UpdateStatusText(hwnd, L"Emulator optimized successfully.");
    } else {
        UpdateStatusText(hwnd, L"No emulator processes optimized.");
    }
}

// Event handler for button click
void OnStartButtonClick(HWND hwnd) {
    std::vector<std::wstring> processNames = {
        L"MuMuPlayer.exe",
        L"MuMuVMMHeadless.exe",
        L"Ld9BoxHeadless.exe",
        L"Ld9BoxSVC.exe",
        L"dnplayer.exe",
        L"HD-Player.exe"
    };

    // Check and modify processes
    CheckAndModifyProcesses(processNames, hwnd);
}

// Function to update the status text in the window
void UpdateStatusText(HWND hwnd, const std::wstring& status) {
    HWND hStatusText = GetDlgItem(hwnd, ID_STATUS_TEXT);
    SetWindowTextW(hStatusText, status.c_str()); // Use SetWindowTextW for wide strings
}
when processes are detected and apply emulator optimization option is shown , below that option add another button named "Fix Lag" which should implement this code when clicked : #include <windows.h>
#include <iostream>
#include <string>

void SetCoreParkingValue(DWORD value) {
    // Path to the core parking registry settings
    const wchar_t* registryPath = L"SYSTEM\\CurrentControlSet\\Control\\Power\\PowerSettings\\0cc5b647-c1bf-4637-891a-7eea1e1ef65c\\";
    
    // Open the registry key
    HKEY hKey;
    LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, registryPath, 0, KEY_WRITE, &hKey);
    
    if (result == ERROR_SUCCESS) {
        // Setting the core parking value
        result = RegSetValueEx(hKey, L"Value", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
        if (result == ERROR_SUCCESS) {
            std::cout << "Successfully updated core parking value." << std::endl;
        } else {
            std::cerr << "Failed to set core parking value." << std::endl;
        }
        RegCloseKey(hKey);
    } else {
        std::cerr << "Failed to open registry key." << std::endl;
    }
}

void ApplyPowerPlan() {
    // GUID for High Performance Power Plan
    const char* highPerfGuid = "{8c5e7e17-1ee8-445a-9d12-1b8289647aa3}";
    
    // Run the powercfg command to set the High Performance power plan
    std::string command = "powercfg /setactive " + std::string(highPerfGuid);
    
    // Execute the command
    if (system(command.c_str()) == 0) {
        std::cout << "Successfully set High Performance power plan." << std::endl;
    } else {
        std::cerr << "Failed to set High Performance power plan." << std::endl;
    }
}

int main() {
    // Disable core parking (set to 0)
    SetCoreParkingValue(0);

    // Apply the High Performance power plan
    ApplyPowerPlan();

    std::cout << "Core parking should now be disabled, and high-performance settings are applied." << std::endl;
    
    return 0;
}