package isrp.model.service.impl;

import isrp.hibernate.model.businessobject.Answersquestions;
import isrp.hibernate.model.businessobject.Paper;
import isrp.hibernate.model.businessobject.Question;
import isrp.hibernate.model.businessobject.Review;
import isrp.hibernate.model.businessobject.User;
import isrp.hibernate.model.dao.AnswersquestionsDao;
import isrp.hibernate.model.dao.PaperDao;
import isrp.hibernate.model.dao.ReviewDao;
import isrp.hibernate.model.dao.UserDao;
import isrp.hibernate.model.dao.factory.DaoFactory;
import isrp.hibernate.model.util.email.EmailConfiguration;
import isrp.hibernate.model.util.email.EmailMessagesUtil;
import isrp.hibernate.model.util.email.EmailSender;
import isrp.model.service.ReviewService;

import java.util.List;

public class ReviewServiceImpl implements ReviewService {

	public ReviewServiceImpl() {

	}

	@SuppressWarnings("unchecked")
	public void addNewReview(Review review, Paper paper,
			List selectedAnswersArray[], List<Question> questions,
			User reviewer, EmailConfiguration emailConfiguration) {
		ReviewDao rDao = DaoFactory.getInstance().getReviewDao();
		PaperDao pDao = DaoFactory.getInstance().getPaperDao();
		UserDao uDao = DaoFactory.getInstance().getUserDao();
		AnswersquestionsDao aqDao = DaoFactory.getInstance()
				.getAnswersquestionsDao();
		rDao.save(review);
		pDao.saveOrUpdate(paper);

		Answersquestions asqu;
		String answerId;
		for (int i = 0; i < questions.size(); i++) {
			if (selectedAnswersArray[i].size() != 0) {
				for (int j = 0; j < selectedAnswersArray[i].size(); j++) {
					asqu = new Answersquestions();
					asqu.setReviewId(review.getId());
					answerId = (String) selectedAnswersArray[i].get(j);
					asqu.setQuestionId(questions.get(i).getId());
					asqu.setAnswerId(Integer.parseInt(answerId));
					aqDao.save(asqu);
				}
			}
		}

		String adminEmail = uDao.getAdministratorEmail();
		User author = (User) uDao.findById(paper.getAuthorId());

		EmailSender eSender = new EmailSender(emailConfiguration);
		eSender.sendEMail(EmailMessagesUtil.newReviewMessage(reviewer, paper,
				adminEmail, "Administrator"));
		eSender.sendEMail(EmailMessagesUtil.newReviewMessage(reviewer, paper,
				author.getEmail(), author.getFirstName() + " "
						+ author.getLastName()));

	}

}
