package com.atmob.voiceai.handlers;

import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.atmob.common.runtime.ContextUtil;
import com.atmob.voiceai.BuildConfig;
import com.atmob.voiceai.sdk.firebase.FirebaseHelper;
import com.atmob.voiceai.utils.ToastUtil;

import java.util.Set;

import dagger.hilt.EntryPoint;
import dagger.hilt.InstallIn;
import dagger.hilt.android.EntryPointAccessors;
import dagger.hilt.components.SingletonComponent;

public final class EventHandler {

    private static boolean isToastReport = false;


    private static volatile EventHandler INSTANCE;
    private final FirebaseHelper firebaseHelper;
    private static Handler MAIN_HANDLER;

    static {
        if (isToastReport) {
            MAIN_HANDLER = new Handler(Looper.getMainLooper());
        }
    }

    private EventHandler() {
        Application application = ContextUtil.getApplication();
        EventHandlerEntryPoint entryPoint = EntryPointAccessors.fromApplication(application, EventHandlerEntryPoint.class);
        firebaseHelper = entryPoint.firebaseHelper();
    }

    public static void setToastReport() {
        isToastReport = true;
        MAIN_HANDLER = new Handler(Looper.getMainLooper());
    }

    private static EventHandler getInstance() {
        if (INSTANCE == null) {
            synchronized (EventHandler.class) {
                if (INSTANCE == null) {
                    INSTANCE = new EventHandler();
                }
            }
        }
        return INSTANCE;
    }

    public static void report(String eventId) {
        report(eventId, null);
    }

    public static void report(String eventId, Bundle params) {
        if (TextUtils.isEmpty(eventId)) {
            return;
        }
        if (isToastReport) {
            MAIN_HANDLER.post(() -> {
                StringBuilder sb = new StringBuilder();
                sb.append(eventId);
                if (params != null) {
                    sb.append(" ");
                    Set<String> keySet = params.keySet();
                    for (String key : keySet) {
                        sb.append(key);
                        sb.append(":");
                        sb.append(params.get(key));
                        sb.append(" ");
                    }
                }
                ToastUtil.show(sb.toString(), ToastUtil.LENGTH_SHORT);
            });
        }
        if (BuildConfig.DEBUG) {
            return;
        }
        getInstance().firebaseHelper.reportEvent(eventId, params);
    }


    @EntryPoint
    @InstallIn(SingletonComponent.class)
    interface EventHandlerEntryPoint {
        FirebaseHelper firebaseHelper();
    }
}