package com.miraclegarden.smsmessage.service;

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class NotificationHealthCheckWorker extends Worker {

    private static final String TAG = "NotiHealthCheck";

    public NotificationHealthCheckWorker(@NonNull Context context, @NonNull WorkerParameters params) {
        super(context, params);
    }

    @NonNull
    @Override
    public Result doWork() {
        if (!isNotificationListenerEnabled()) {
            Log.w(TAG, "notification listener disabled, attempting recovery");
            NotificationService.toggleNotificationListenerService(getApplicationContext());
        } else {
            Log.d(TAG, "notification listener ok");
        }
        return Result.success();
    }

    private boolean isNotificationListenerEnabled() {
        String flat = Settings.Secure.getString(
                getApplicationContext().getContentResolver(),
                "enabled_notification_listeners");
        if (TextUtils.isEmpty(flat)) {
            return false;
        }
        return flat.contains(getApplicationContext().getPackageName());
    }
}
