/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.snippet.telecom;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

import android.os.SystemClock;
import androidx.annotation.NonNull;
import com.google.android.mobly.snippet.event.EventCache;
import com.google.android.mobly.snippet.event.SnippetEvent;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import java.util.function.Supplier;

/** Utility class for waiting for conditions to be met. */
final class WaitUtils {
  private static final long DEFAULT_CPU_SLEEP_MS = 100L;

  private static final Ticker ANDROID_SYSTEM_TICKER =
      new Ticker() {
        @Override
        public long read() {
          return SystemClock.elapsedRealtimeNanos();
        }
      };

  public static void waitUntilTrue(
      @NonNull Supplier<Boolean> supplier, long timeoutInMillis, String errorMessage)
      throws TimeoutException {
    final long endTime = SystemClock.uptimeMillis() + timeoutInMillis;
    do {
      if (supplier.get()) {
        return;
      }
      SystemClock.sleep(DEFAULT_CPU_SLEEP_MS);
    } while (SystemClock.uptimeMillis() < endTime);
    throw new TimeoutException(errorMessage);
  }

  @CanIgnoreReturnValue
  public static SnippetEvent waitForSnippetEvent(
      String callbackId,
      String eventName,
      long timeoutMs,
      Predicate<SnippetEvent> predicate,
      String errorMessage)
      throws TimeoutException {
    String qId = EventCache.getQueueId(callbackId, eventName);
    SnippetEvent snippetEvent;
    Stopwatch stopwatch = Stopwatch.createStarted(ANDROID_SYSTEM_TICKER);
    do {
      snippetEvent = EventCache.getInstance().getEventDeque(qId).pollFirst();
      if (snippetEvent != null && predicate.test(snippetEvent)) {
        return snippetEvent;
      }
    } while (Duration.ofMillis(stopwatch.elapsed(MILLISECONDS))
            .compareTo(Duration.ofMillis(timeoutMs))
        < 0);
    throw new TimeoutException(errorMessage);
  }

  private WaitUtils() {}
}

