package test;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import datasource.DB;
import datasource.PersonMapper;
import model.Person;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class PersonMapperTest {
        @Test
        public void DataManipulation() throws Exception {
                PersonMapper personMapper = new PersonMapper();
                Person john = new Person(0, "Lennon", "John", 1);
                
                // Test insertion
                personMapper.insert(john);
                Person foundJohn = personMapper.find(0);
                assertThat(foundJohn.getId(), is(0L));
                assertThat(foundJohn.getLastName(), is("Lennon"));
                assertThat(foundJohn.getFirstName(), is("John"));
                assertThat(foundJohn.getNumberOfDependents(), is(1L));

                // Test update
                john.setNumberOfDependents(2);
                personMapper.update(john);
                foundJohn = personMapper.find(0);
                assertThat(foundJohn.getNumberOfDependents(), is(2L));

                // Test find 
                List<Person> persons = personMapper.findByLastName("Lennon");
                assertThat(persons.size(), is(1));
                persons = personMapper.findByLastName("Star");
                assertThat(persons.size(), is(0));

                // Test deletion
                personMapper.delete(john);
                persons = personMapper.findByLastName("Lennon");
                assertThat(persons.size(), is(0));
        }

        @Before
        public void Preparation() throws SQLException {
                Statement stmt = DB.createStatement();
                stmt.execute("DROP TABLE IF EXISTS persons");
                stmt.execute("CREATE TABLE persons ( id BIGINT PRIMARY KEY, "
                                + "lastname VARCHAR(32), firstname VARCHAR(32), dependents BIGINT )");
        }

        @BeforeClass
        public static void DBPreProcessing() throws Exception {
                DB.init();
        }

        @AfterClass
        public static void DBPostProcessing() throws Exception {
                DB.terminate();
        }	
} 
