package com.vsu.fcounter.autoclick;

import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;

public class AutoClickModule extends ReactContextBaseJavaModule {

    ReactContext context;
    static AutoClickModule instance;

    public static AutoClickModule getInstance() {
        return instance;
    }

    public static AutoClickModule getInstance(ReactContext context) {
        instance = new AutoClickModule(context);
        return instance;
    }

    @NonNull
    @Override
    public String getName() {
        return "AutoClick";
    }

    AutoClickModule(ReactContext context) {
        this.context = context;
    }

    @ReactMethod
    void isSettingsOn(Promise promise) {
        int accessibilityEnabled = 0;
        final String service = context.getPackageName() + "/" + AutoClickService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                boolean enable = false;
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        enable = true;
                        break;
                    }
                }
                promise.resolve(enable);
            }
        } else promise.resolve(false);
    }

    @ReactMethod
    void goSetting(Promise promise) {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @ReactMethod
    void setEvent(String name, ReadableMap event, Promise promise) {
        AccessibilityOperator.getInstance().setEvent(name, event);
        promise.resolve(true);
    }

    @ReactMethod
    void clickBackKey(Promise promise) {
        AccessibilityOperator.getInstance().clickBackKey();
        promise.resolve(true);
    }

}
