#include "ru_yandex_webmaster3_core_host_service_HostCanonizer.h"

#include <kernel/hosts/owner/owner.h>
#include <yweb/antispam/common/owner/owner.h>

namespace NWebmaster {

struct TCanonizerHolder {
public:
    TOwnerCanonizer KernelOwnerCanonizer;
    TMascotOwnerCanonizer MascotOwnerCanonizer;
private:
    Y_DECLARE_SINGLETON_FRIEND();

    TCanonizerHolder()
    {
        KernelOwnerCanonizer.LoadTrueOwners();
        KernelOwnerCanonizer.LoadSerpCategOwners();
        MascotOwnerCanonizer.LoadTrueOwners();
    }

public:
    static TCanonizerHolder* Instance() {
        return Singleton<TCanonizerHolder>();
    }
};

} //namespace NWebmaster

using namespace NWebmaster;

jint JNI_OnLoad(JavaVM* jvm, void*) {
    JNIEnv* env;
    if (jvm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }
    return JNI_VERSION_1_6;
}

template <class TCanonizer>
jstring getOwner(const TCanonizer &canonizer, JNIEnv *env, jstring host, bool needUrl) {
    const char* hostStr = env->GetStringUTFChars(host, nullptr);
    if (nullptr == hostStr) {
        return nullptr;
    }
    TString owner;
    if (needUrl) {
        owner = canonizer.GetUrlOwner(hostStr);
    } else {
        owner = canonizer.GetHostOwner(hostStr);
    }
    env->ReleaseStringUTFChars(host, hostStr);
    return env->NewStringUTF(owner.c_str());
}

/*
 * Class:     ru_yandex_webmaster3_core_host_service_HostCanonizer
 * Method:    getHostOwner
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_ru_yandex_webmaster3_core_host_service_HostCanonizer_getHostOwner
    (JNIEnv *env, jclass, jstring host)
{
    return getOwner(TCanonizerHolder::Instance()->KernelOwnerCanonizer, env, host, false);
}

/*
 * Class:     ru_yandex_webmaster3_core_host_service_HostCanonizer
 * Method:    getMascotHostOwner
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_ru_yandex_webmaster3_core_host_service_HostCanonizer_getMascotHostOwner
    (JNIEnv *env, jclass, jstring host)
{
    return getOwner(TCanonizerHolder::Instance()->MascotOwnerCanonizer, env, host, false);
}

/*
 * Class:     ru_yandex_webmaster3_core_host_service_HostCanonizer
 * Method:    getUrlOwner
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_ru_yandex_webmaster3_core_host_service_HostCanonizer_getUrlOwner
    (JNIEnv *env, jclass, jstring host)
{
    return getOwner(TCanonizerHolder::Instance()->KernelOwnerCanonizer, env, host, true);
}

/*
 * Class:     ru_yandex_webmaster3_core_host_service_HostCanonizer
 * Method:    getMascotUrlOwner
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_ru_yandex_webmaster3_core_host_service_HostCanonizer_getMascotUrlOwner
    (JNIEnv *env, jclass, jstring host)
{
    return getOwner(TCanonizerHolder::Instance()->MascotOwnerCanonizer, env, host, true);
}
