package com.example.applock.allmanager;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;

import com.example.applock.roombase.AppDataBase;
import com.example.applock.roombase.AppEntity;
import com.example.applock.roombase.SoftWareLockRoom;

import java.util.Objects;

public class MyWorker extends JobIntentService {
    private String lastLockPackName = "";
    private LockAction lockAction;
    private Boolean isTop = true;

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, MyWorker.class, 23, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        lockAction = LockAction.getActionInstance(this);
        while (isTop) {
            String packageName = AppManager.getUsage(this);
            if (Objects.equals(packageName, "")) {
                continue;
            }
            AppEntity entityApp = AppDataBase.getDatabaseInstance().getAppEntityDao().queryByPagName(packageName);
            if (entityApp == null) {
                lockAction.HideLockView();
                lastLockPackName = packageName;
                continue;
            }
            if (Objects.equals(packageName, lastLockPackName)) {
                continue;
            }
            if (entityApp.isApplocked()) {
                if (!Objects.equals(packageName, lastLockPackName)) {
                    SoftWareLockRoom.onRunMain(() -> {
                        lockAction.showLockView();
                    });
                } else {

                }
            } else {
                SoftWareLockRoom.onRunMain(() -> {
                    lockAction.HideLockView();
                });
            }
            lastLockPackName = packageName;
        }


    }
}
