/*
 * Copyright 2020 the original author or authors.
 *
 * 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
 *
 *     https://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 example.app.books.service.support;

import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import example.app.books.model.Book;
import example.app.books.model.ISBN;
import example.app.books.repo.BookRepository;
import example.app.books.service.BookService;

/**
 * The {@link CachingBookService} class is an implementation and extension of {@link BookService}
 * with caching capabilities.
 *
 * @author John Blum
 * @see example.app.books.model.Book
 * @see example.app.books.model.ISBN
 * @see example.app.books.repo.BookRepository
 * @see example.app.books.service.BookService
 * @see org.springframework.cache.annotation.Cacheable
 * @see org.springframework.stereotype.Service
 * @since 1.0.0
 */
@Service
public class CachingBookService extends BookService {

	private final AtomicBoolean cacheMiss = new AtomicBoolean(false);

	public CachingBookService(@Autowired(required = false) BookRepository bookRepository) {
		super(bookRepository);
	}

	public boolean isCacheMiss() {
		return this.cacheMiss.getAndSet(false);
	}

	@Override
	@Cacheable(value = "CachedBooks")
	public Book findByTitle(String title) {
		this.cacheMiss.set(true);
		return Book.newBook(title).identifiedBy(ISBN.autoGenerated());
	}
}
