package persistence;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import persistence.category.CategoryEntity;

import java.io.File;
import java.io.IOException;

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

class GenericCSVDAOTest {

	GenericCSVDAO<CategoryEntity> sut;
	File file = File.createTempFile("test","link-ditch");

	GenericCSVDAOTest() throws IOException {
	}

	@BeforeEach
	public void beforeEach() throws IOException {

		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();

		this.sut = new GenericCSVDAO<>(file, CategoryEntity::new);
	}

	@AfterEach
	void afterEach() {
		file.delete();
	}

	@Test
	public void addWorks() throws IOException {
		assertEquals(0, sut.getAll().size());

		CategoryEntity entityToAdd = addDummyEntity("categoryName", 99);
		var foundEntity = sut.getAll().stream().findFirst().orElseThrow();

		assertEquals(entityToAdd, foundEntity);
	}

	@Test
	public void removeWorks() throws IOException {
		CategoryEntity entityToAdd = addDummyEntity("categoryName", 99);

		sut.remove(entityToAdd);

		assertEquals(0, sut.getAll().size());
	}


	@Test
	public void removeAllWorks() throws IOException {
		addDummyEntity("categoryName1", 101);
		addDummyEntity("categoryName2", 102);
		assertEquals(2, sut.getAll().size());
		sut.removeAll();

		assertEquals(0, sut.getAll().size());
	}

	private CategoryEntity addDummyEntity(String categoryName, int id) {
		var entityToAdd = new CategoryEntity(categoryName, id);
		sut.add(entityToAdd);
		return entityToAdd;
	}
}
