/*
 * Profile.java
 *
 * Autor: Karolina Sołtys
 */
package dendrarium.portal.profile;

import dendrarium.core.entities.Answer;
import dendrarium.trees.AnswerType;
import dendrarium.core.entities.Packet;
import dendrarium.core.entities.TaskBusinessProcess;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.FlushModeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

/**
 *
 * @author Dominika Pawlik
 */
@Name("packetProfile")
@Scope(ScopeType.CONVERSATION)
public class PacketProfile implements Serializable {

    public enum UserAnswerType {

        CLEAN,
        INPROGRESS,
        FULL,
        SPECIAL
    }

    @In
    Identity identity;

    @In
    Session session;

    @Logger
    Log log;

    @In(required = false)
    @Out
    Packet p;

    private List<TaskBusinessProcess> packetTasks;

    @Begin(join = true, flushMode = FlushModeType.MANUAL)
    public void select(Packet packet) {
        this.p = packet;
        getPacketTasks();
    }

    public UserAnswerType getTypeAnswer(Answer answer) {
        if (answer == null) {
            return UserAnswerType.CLEAN;
        } else if (answer.isAccepted()) {
            if (answer.getType() == AnswerType.FULL) {
                return UserAnswerType.FULL;
            } else {
                return UserAnswerType.SPECIAL;
            }
        } else {
            return UserAnswerType.INPROGRESS;
        }
    }

    public boolean isCollisions() {
        return false;
    }

    public Packet getPacket() {
        return p;
    }

    public TaskBusinessProcess getFirstTBP() {
        return getPacketTasks().get(0);
    }

    public List<TaskBusinessProcess> getPacketTasks() {
        if (packetTasks == null) {
            packetTasks = session.createQuery("from TaskBusinessProcess tbp where tbp.current = TRUE and tbp.packet = :packet order by tbp.index").setEntity("packet", getPacket()).list();
        }
        return packetTasks;
    }

    public void setPacket(Packet p) {
        this.p = p;
    }
}
