package com.gmscheduler.unittests;

import junit.framework.TestCase;
import junit.framework.Assert;

import com.gmscheduler.model.HibernateUtil;
import com.gmscheduler.model.Person;
import com.gmscheduler.model.Timeframe;
import com.gmscheduler.model.Schedule;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import org.hibernate.Session;

public class ScheduleTest extends TestCase {

	private Person p1;
	private Timeframe t1;
	private Schedule s1;
	private Schedule s2;
	private Person p3;
	private Timeframe t3;
	private Schedule s3;
	private Timeframe t4;
	private LinkedList lt4;
	private Schedule s4,s5;
	private Schedule ls;
	
	protected void setUp() throws Exception {
		p1 = new Person("John");
		t1 = new Timeframe("M","10:00am","1:00pm");
		s1 = new Schedule(p1,t1);
		s2 = new Schedule(s1);
		Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
		session2.beginTransaction();
		p3 = new Person("Mary Jo");
		session2.save(p3);
		t3 = new Timeframe("M","10:00am","1:00pm");
		s3 = new Schedule(p3);
		session2.save(s3);
		s3.addTimeframe(t3);
		t4 = new Timeframe("T","4:00pm","5:00pm");
		lt4 = new LinkedList();
		lt4.add(t1);
		lt4.add(t4);
		s4 = new Schedule(p3);
		session2.save(s4);
		s4.add(lt4);
		session2.save(t1);
		session2.save(t4);
		session2.getTransaction().commit();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void testScheduleEquals() {
		Assert.assertEquals(s1.toString(),s2.toString());
		Assert.assertTrue(!s4.equals(s3));
	}
	
	public void testScheduleSaveAndLoad() {		
		Long stid = new Long(s4.getId());
		System.out.println(s4.getId());
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		ls = (Schedule)session.load(Schedule.class,stid);
		List result = session.createQuery(
				"from Timeframe as timeframe " +
					"where timeframe.scheduleid = " + ls.getId().toString()).list();
		ListIterator lils = result.listIterator();
		
		do {
			ls.addTimeframe((Timeframe)lils.next());
		} while (lils.hasNext());
		
		String lts = new String(ls.toString());
		session.getTransaction().commit();
		
		Assert.assertEquals(s4.toString(),lts);
	}
	
	public void testScheduleTimeframeRemove() {		
		s5 = new Schedule (p3,t3);
		s4.removeTimeframe(t4);

		Assert.assertEquals(s5.toString(),s4.toString());		
	}
}
