package dst.ass1.jpa.tests;

import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.persistence.EntityTransaction;

import org.junit.Before;
import org.junit.Test;

import dst.ass1.jpa.dao.ICourseDAO;
import dst.ass1.jpa.model.CourseStatus;
import dst.ass1.jpa.model.ICourse;

public class Ass1_2_3b_02Test extends Ass1_TestBase {

    private ICourseDAO dao;

    @Before
    public void setUp() throws Exception {
        dao = daoFactory.createCourseDAO();

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        ICourse course1 = dao.findById(testData.course1Id);
        course1.setStatus(CourseStatus.CANCELLED);
        em.persist(course1);
        em.flush();
        tx.commit();
    }

    @Test
    public void testFindNonCancelledCoursesBetweenStartAndFinish() {
        Collection<ICourse> courses = dao.findNonCancelledCoursesBetweenStartAndEnd(null, null);

        assertThat(map(courses, e -> e.getId()), hasItems(
                testData.course2Id
        ));
    }

    @Test
    public void testFindEventsForStatusFinishedBetweenStartAndFinish2() {
        Date start = createDate(2017, 1, 1, 1, 1);
        Collection<ICourse> courses = dao.findNonCancelledCoursesBetweenStartAndEnd(start, null);

        assertThat(map(courses, e -> e.getId()), hasItems(
                testData.course2Id
        ));
    }

    @Test
    public void testFindEventsForStatusFinishedBetweenStartAndFinish3() {
        Date end = dao.findById(testData.course2Id).getEnd();
        Collection<ICourse> courses = dao.findNonCancelledCoursesBetweenStartAndEnd(null, end);
        assertNotNull(courses);
        assertTrue(courses.isEmpty());
    }

    private Date createDate(int year, int month, int day, int hours, int minutes) {
        return new GregorianCalendar(year, month, day, hours, minutes).getTime();
    }

}
