/*
    PIP - Platform Independent Primitives
    Global includes
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "piincludes.h"

#include "piincludes_p.h"
#include "pitime.h"
#ifndef QNX
#  include <clocale>
#else
#  include <locale.h>
#endif
#ifdef MAC_OS
// #  include <mach/mach_traps.h>
// #  include <mach/mach.h>
#  include <mach/clock.h>
// #  include <crt_externs.h>
#endif
#include <errno.h>

bool piDebug                        = true;
double piMountInfoRefreshIntervalMs = 10000.;

lconv * currentLocale =
#ifdef ANDROID
	0;
#else
	std::localeconv();
#endif

#ifdef MAC_OS
clock_serv_t __pi_mac_clock;
#endif

#ifdef WINDOWS
FILETIME __pi_ftjan1970;
long long __pi_perf_freq                        = -1;
PINtQueryTimerResolution getTimerResolutionAddr = 0;
PINtSetTimerResolution setTimerResolutionAddr   = 0;
#endif

void errorClear() {
#ifdef WINDOWS
	SetLastError(0);
#else
	errno = 0;
#endif
}

PIString errorString() {
#ifdef WINDOWS
	char * msg = nullptr;
	int err    = GetLastError();
	FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	               NULL,
	               err,
	               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
	               (LPSTR)&msg,
	               0,
	               NULL);
	PIString ret = PIStringAscii("code ") + PIString::fromNumber(err) + PIStringAscii(" - ");
	if (msg) {
		ret += PIString::fromSystem(msg).trim();
		LocalFree(msg);
	} else
		ret += '?';
	return ret;
#else
	int e = errno;
	return PIString("code ") + PIString::fromNumber(e) + " - " + PIString(strerror(e));
#endif
}

PIString PIPVersion() {
	static PIString ret = PIStringAscii(PIP_VERSION_NAME);
	return ret;
}


void randomize() {
	srand(PISystemTime::current(true).nanoseconds);
}


int randomi() {
	return rand();
}
