
#ifndef ETHERCAT_STATICS_AUTHORIZATION_H
#define ETHERCAT_STATICS_AUTHORIZATION_H

#pragma once

#include "../ethercat_types.h"
#include <stdint.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#endif

#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
    LICENSE_NOT_VERIFIED      = 0,
    LICENSE_VERIFYING         = 1,
    LICENSE_VERIFIED          = 2,
    LICENSE_FAILED            = 3,
    LICENSE_EXPIRED           = 4,
    LICENSE_MACHINE_MISMATCH  = 5,
    LICENSE_TIME_ROLLBACK     = 6
} dx_license_status_t;

typedef int (*PFN_DARRA_GET_LICENSE_STATUS)(void);

static inline dx_license_status_t license_get_status(void) {
#ifdef _WIN32
    HMODULE h = GetModuleHandleA("Darra.Core.dll");
    if (!h) h = LoadLibraryA("Darra.Core.dll");
    if (!h) {
        return LICENSE_NOT_VERIFIED;
    }

    PFN_DARRA_GET_LICENSE_STATUS fn =
        (PFN_DARRA_GET_LICENSE_STATUS)GetProcAddress(h, (LPCSTR)1737);
    if (!fn) fn = (PFN_DARRA_GET_LICENSE_STATUS)GetProcAddress(h, "D_1737");
    if (!fn) {
        return LICENSE_NOT_VERIFIED;
    }
    int raw = fn();

    if (raw >= (int)LICENSE_NOT_VERIFIED && raw <= (int)LICENSE_TIME_ROLLBACK) {
        return (dx_license_status_t)raw;
    }
    return LICENSE_NOT_VERIFIED;
#else

    return LICENSE_NOT_VERIFIED;
#endif
}

typedef int (*PFN_DARRA_LICENSE_ACTIVATE)(const char* activation_code, char* err_buf, int err_buf_len);

static inline int license_activate(const char* activation_code, char* err_buf, int err_buf_len) {
#ifdef _WIN32
    HMODULE h = GetModuleHandleA("Darra.Core.dll");
    if (!h) h = LoadLibraryA("Darra.Core.dll");
    if (!h) {
        if (err_buf && err_buf_len > 0) {
            const char* m = "Darra.Core.dll \xe6\x9c\xaa\xe5\x8a\xa0\xe8\xbd\xbd";
            int n = (int)strlen(m); if (n >= err_buf_len) n = err_buf_len - 1;
            memcpy(err_buf, m, n); err_buf[n] = '\0';
        }
        return 3;
    }

    PFN_DARRA_LICENSE_ACTIVATE fn = (PFN_DARRA_LICENSE_ACTIVATE)GetProcAddress(h, (LPCSTR)1599);
    if (!fn) fn = (PFN_DARRA_LICENSE_ACTIVATE)GetProcAddress(h, "D_1599");
    if (!fn) {
        if (err_buf && err_buf_len > 0) {
            const char* m = "\xe6\xbf\x80\xe6\xb4\xbb\xe5\x85\xa5\xe5\x8f\xa3\xe6\x9c\xaa\xe5\xaf\xbc\xe5\x87\xba";
            int n = (int)strlen(m); if (n >= err_buf_len) n = err_buf_len - 1;
            memcpy(err_buf, m, n); err_buf[n] = '\0';
        }
        return 3;
    }
    return fn(activation_code, err_buf, err_buf_len);
#else

    if (err_buf && err_buf_len > 0) {
        const char* m = "Linux not supported";
        int n = (int)strlen(m); if (n >= err_buf_len) n = err_buf_len - 1;
        memcpy(err_buf, m, n); err_buf[n] = '\0';
    }
    return 3;
#endif
}

#ifdef __cplusplus
}
#endif

#endif
