package com.android.dialer.app.calllog;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import com.android.dialer.common.LogUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** Background execution for call-history retention. */
public final class CallHistoryRetentionJobService extends JobService {

  private ExecutorService worker;

  static void runCleanupAsync(Context context, Runnable completion) {
    ExecutorService executor =
        Executors.newSingleThreadExecutor(
            runnable -> new Thread(runnable, "LemenzoCallHistoryRetention"));
    executor.execute(
        () -> {
          try {
            CallHistoryRetentionManager.deleteExpired(context);
          } finally {
            if (completion != null) {
              completion.run();
            }
            executor.shutdown();
          }
        });
  }

  @Override
  public boolean onStartJob(JobParameters params) {
    LogUtil.enterBlock("CallHistoryRetentionJobService.onStartJob");
    worker =
        Executors.newSingleThreadExecutor(
            runnable -> new Thread(runnable, "LemenzoCallHistoryRetentionJob"));
    worker.execute(
        () -> {
          try {
            CallHistoryRetentionManager.deleteExpired(getApplicationContext());
          } finally {
            jobFinished(params, false);
          }
        });
    return true;
  }

  @Override
  public boolean onStopJob(JobParameters params) {
    if (worker != null) {
      worker.shutdownNow();
    }
    return true;
  }

  @Override
  public void onDestroy() {
    if (worker != null) {
      worker.shutdownNow();
    }
    super.onDestroy();
  }
}
