package org.cache2k.test.core;

/*-
 * #%L
 * cache2k core implementation
 * %%
 * Copyright (C) 2000 - 2022 headissue GmbH, Munich
 * %%
 * 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.
 * #L%
 */

import org.cache2k.Cache;
import org.cache2k.Cache2kBuilder;
import org.cache2k.event.CacheEntryRemovedListener;
import org.cache2k.core.api.InternalCache;
import org.cache2k.core.api.InternalCacheInfo;

import static org.assertj.core.api.Assertions.assertThat;
import static org.cache2k.CacheManager.getInstance;

/**
 * @author Jens Wilke
 */
public class StaticUtil {

  public static InternalCacheInfo latestInfo(Cache c) {
    return ((InternalCache) c).getConsistentInfo();
  }

  /**
   * Enforce the usage of wired cache by registering a dummy listener.
   */
  @SuppressWarnings("unchecked")
  public static <K, V> Cache2kBuilder<K, V> enforceWiredCache(Cache2kBuilder<K, V> b) {
    return b.addListener((CacheEntryRemovedListener<K, V>) (cache, entry) -> {
    });
  }

  public static void allCachesClosed() {
    assertThat(getInstance().getActiveCaches().iterator().hasNext())
      .as("all caches closed")
      .isFalse();
  }

  public static int count(Iterable<?> things) {
    int count = 0;
    for (Object o : things) {
      count++;
    }
    return count;
  }

}
