package de.thpeetz.kontor.bookshelf.data;

import de.thpeetz.kontor.bookshelf.TestConstants;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Disabled
class BookRepositoryTest {

    @Autowired
    BookRepository bookRepository;

    @Autowired
    BookshelfPublisherRepository bookshelfPublisherRepository;

    @Test
    @Order(1)
    void checkInitialLoad(){
        assertEquals(TestConstants.BOOK_COUNT, bookRepository.findAll().size());
    }

    @Test
    @Order(2)
    void saveBook() {
        BookshelfPublisher publisher = new BookshelfPublisher();
        publisher.setName(TestConstants.PUBLISHER_NAME);
        bookshelfPublisherRepository.save(publisher);
        Book book = new Book();
        book.setTitle(TestConstants.BOOK_TITLE);
        book.setIsbn(TestConstants.BOOK_ISBN);
        book.setPublisher(publisher);
        bookRepository.save(book);
        assertEquals(TestConstants.BOOK_COUNT+1, bookRepository.findAll().size());
    }

    @Test
    @Order(3)
    void search() {
        List<Book> books = bookRepository.search(TestConstants.BOOK_TITLE.substring(2,5));
        assertEquals(1, books.size());
        assertEquals(1, bookRepository.search(TestConstants.BOOK_ISBN.substring(3,7)).size());
        assertEquals(0, bookRepository.search("Article").size());
    }

    @Test
    @Order(4)
    void findByTitle() {
        List<Book> books = bookRepository.findByTitle(TestConstants.BOOK_TITLE);
        assertEquals(1, books.size());
        assertEquals(TestConstants.BOOK_ISBN, books.get(0).getIsbn());
    }

    @Test
    @Order(5)
    void findByTitleIgnoreCase() {
        List<Book> books = bookRepository.findByTitleIgnoreCase(TestConstants.BOOK_TITLE.toLowerCase());
        assertEquals(1, books.size());
        assertEquals(TestConstants.BOOK_ISBN, books.get(0).getIsbn());
    }

    @Test
    @Order(6)
    void findByIsbn() {
        List<Book> books = bookRepository.findByIsbn(TestConstants.BOOK_ISBN);
        assertEquals(1, books.size());
        assertEquals(TestConstants.BOOK_TITLE, books.get(0).getTitle());
    }

    @Test
    @Order(7)
    void deleteBook() {
        List<Book> books = bookRepository.findByIsbn(TestConstants.BOOK_ISBN);
        Book book = books.get(0);
        BookshelfPublisher publisher = book.getPublisher();
        bookshelfPublisherRepository.delete(publisher);
        bookRepository.delete(book);
        assertEquals(TestConstants.BOOK_COUNT, bookRepository.findAll().size());
        assertEquals(TestConstants.PUBLISHER_COUNT, bookshelfPublisherRepository.findAll().size());
    }
}