//
//  main.m
//  JavaJDKTest
//
//  Created by eren on 2024/5/16.
//

#import <Foundation/Foundation.h>
#include <jni.h>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <iostream>


std::string workPath = "";

std::string GetCurrentTime(std::string type)
{
    time_t now = time(0);
    struct tm  tstruct;
    char  buf[80];
    tstruct = *localtime(&now);
    if (type =="now")
        strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
    else if (type =="date")
        strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct);
    return std::string(buf);
}


void WriteLog(const std::string& message)
{
    const std::string logFolder = workPath;
    const std::string path = logFolder + "/" + GetCurrentTime("date") + "_log.txt";
    std::ofstream log(path, std::ios_base::out | std::ios_base::app);
    if (log) {
        const std::string now = GetCurrentTime("now");
        log<<now<<'\t'<<message<<std::endl;
        log.close();
    } else {
        std::cout<<strerror(errno)<<std::endl;
    }
}


void initializePolicyController(const std::string& workingFolder)
{
    JavaVM *PDP_jvm = NULL;
    JNIEnv* PDP_env = NULL;
    workPath = workingFolder;
    
    JavaVMOption options[5] = { 0 };
    //options[0].optionString = strdup(("-Djava.class.path=" + workingFolder + "/jlib/agent-controlmanager.jar").c_str());
    //options[1].optionString = strdup(("-Djava.util.logging.config.file=" + workingFolder + "/config/logging.properties").c_str());
    //options[2].optionString = strdup("-Dnextlabs.dont.care.acceptable=true");
    options[0].optionString = strdup("-Xmx512m");
    options[1].optionString = strdup("-Xrs");
    
    JavaVMInitArgs vm_args = { 0 };
    vm_args.version = JNI_VERSION_21;
    vm_args.nOptions = 2;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;
    
    long status = JNI_CreateJavaVM(&PDP_jvm, (void**)&PDP_env, &vm_args);
    if (status != JNI_OK)
    {
      fprintf(stderr, "create JVM failed\n");
        //WriteLog("create JVM failed");
        return;
    }
  fprintf(stderr, "create JVM OK\n");
    //WriteLog("create JVM success");
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        initializePolicyController("/Users/erenshi/SampleCode/JavaRun");
        NSLog(@"Hello, World!");
    }
    return 0;
}
