/** @file platform/windows.c  Windows platform specific routines.

@authors Copyright (c) 2017-2023 Jaakko Keränen <jaakko.keranen@iki.fi>

@par License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

<small>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</small>
*/

#include "the_Foundation/defs.h"
#include <stdio.h>

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#if defined (iPlatformWindows)
#  include <winsock2.h>
#  include "win32/wide.h"
#endif

int idealConcurrentCount_Thread(void) {
    static int ncpu;
    if (ncpu == 0) {
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        ncpu = sysinfo.dwNumberOfProcessors;
    }
    return ncpu;
}

#if !defined (iPlatformMsys) && !defined (iPlatformCygwin)
void init_Locale(void) {
    char cpName[16];
    /* Encoding for 8-bit strings (ANSI C API): fopen, command line, environment, etc. */ {
        unsigned int cp = GetACP();
        sprintf(cpName, "CP%u", cp);
        setLocalEncoding_String(cp == 65001 ? "UTF-8" : cpName);
    }
    /* Console output has its own code page. */ {
        unsigned int cp = GetConsoleOutputCP();
        sprintf(cpName, "CP%u", cp);
        setConsoleEncoding_String(cp == 65001 ? "UTF-8" : cpName);
    }
}
#endif

#if defined (iPlatformWindows)
void init_Windows_(void) {
    /* Initialize Windows Sockets. */
    WSADATA wsInfo;
    int result = WSAStartup(MAKEWORD(2, 2), &wsInfo);
    if (result) {
        MessageBoxA(NULL,
                    errorMessage_Windows_(result),
                    "the_Foundation " iFoundationLibraryVersionCStr,
                    MB_ICONERROR);
        exit(1);
    }
}

void deinit_Windows_(void) {
    WSACleanup();
}
#endif
