package dendrarium.portal.answer;

import dendrarium.core.entities.Answer;
import java.io.Serializable;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.RaiseEvent;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.log.Log;

@Name("workOnAnswerStateless")
@Scope(ScopeType.STATELESS)
public class WorkOnAnswerStateless implements Serializable {

    /* injected fields */
    @In
    Session session;

    @RequestParameter
    Long answerId;

    @Logger
    Log log;

    @RaiseEvent("tbpchangestate")
    public void cancel() {
        Answer answer = (Answer) session.get(Answer.class, answerId);
        cancel(answer);
    }

    @RaiseEvent("tbpchangestate")
    public void cancel(Answer answer) {
        /* edit pta */
        if (answer.getTaskBusinessProcess().getSuperAnswer() != null && answer.getTaskBusinessProcess().getSuperAnswer().getUser() == null) {
            log.info("HISTORIA: usuwamy automatyczną superodpowiedź "+answer.getTaskBusinessProcess().getSuperAnswer().getId()+" z powodu cofnięcia odpowiedzi " + answer.getId());
            session.delete(answer.getTaskBusinessProcess().getSuperAnswer());
            answer.getTaskBusinessProcess().setSuperAnswer(null);
        }

        answer = (Answer) session.merge(answer);
        answer.setAnswer(null);
        answer.getTaskBusinessProcess().updateState();
        session.flush();
        log.info("HISTORIA: dendrolog wycofał odpowiedź " + answer.getId());
        log.info(answer.info());
    }
}
