package inc.monsters.mias.controller;

import inc.monsters.mias.data.Employee;
import inc.monsters.mias.data.Kid;
import inc.monsters.mias.data.facade.EmployeeService;
import inc.monsters.mias.data.facade.KidService;

import java.util.logging.Logger;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.myfaces.orchestra.conversation.Conversation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class EditKidController {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");

	private KidService kidService;
	private EmployeeService employeeService;
	
	private Kid selectedKid;
	
	public KidService getKidService() {
		return kidService;
	}

	public void setKidService(KidService kidService) {
		this.kidService = kidService;
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public EditKidController() {
		log.info("EditKidController() contsructor called");
	}

	@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
	public Kid getSelectedKid() {
		if(null == selectedKid) {
			FacesContext context = FacesContext.getCurrentInstance();
			
	        Kid k = (Kid)context.getExternalContext().getRequestMap().get("selectedKid");
	        selectedKid = kidService.getKidById(k.getId());
	        log.info("selectedKid = " + selectedKid);
		}
		return selectedKid;
	}

	public void setSelectedKid(Kid selectedKid) {
		this.selectedKid = selectedKid;
	}

	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public void saveSelected(ActionEvent event) {
		Kid k = getSelectedKid();
	    log.fine("Saving kid " + k.getId() + ": " + k.getFirstName() + " " + k.getLastName() + ".");
	    if(kidService.existsKid(k)) {
	    	kidService.updateKid(k);	
	    } else {
	    	kidService.addKid(k);
	    }
	}
	
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public void updateScareData(ActionEvent event) {
		Kid k = getSelectedKid();
		Employee e = employeeService.getEmployeeById(k.getEmployee().getId());
		e.increaseKidsScared();
	}
	
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public void endConversationAndSave(ActionEvent event) {
		saveSelected(event);
		endConversation(event);
	}

	public void endConversation(ActionEvent event) {
		Conversation.getCurrentInstance().invalidate();
	}
}
