/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.security.SecUser;
import oneit.servlets.forms.RedisplayResult;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessFormProcessor;
import oneit.servlets.process.ORMProcessState;
import oneit.utils.BusinessException;
import performa.orm.CultureCriteria;
import performa.orm.CultureCriteriaTemplate;
import performa.orm.Job;

/**
 *
 * @author nilu
 */
public class SaveCultureTemplateFP extends ORMProcessFormProcessor
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        final   HttpServletRequest  request     =   submission.getRequest();
        ObjectTransaction           objTran     =   process.getTransaction();
        CultureCriteriaTemplate     template    =   (CultureCriteriaTemplate) request.getAttribute("CultureCriteriaTemplate");
        Job                         job         =   (Job) process.getAttribute("Job");
        
        LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, "Inside SaveCultureTemplateFP for create new template.");
            
        objTran.runInNewTX((ObjectTransaction newObjTran) -> {
            
            CultureCriteriaTemplate newTemplate  = CultureCriteriaTemplate.createCultureCriteriaTemplate(newObjTran);
            
            newTemplate.setTemplateName(template.getTemplateName());
            newTemplate.setUser(SecUser.getTXUser(newObjTran));
            
            for(CultureCriteria criteria : job.getCultureCriteriasSet())
            {
                CultureCriteria criteriaCopy = CultureCriteria.createCultureCriteria(newObjTran);

                criteriaCopy.setCultureElement(criteria.getCultureElement().getInTransaction(newObjTran));
                criteriaCopy.setImportance(criteria.getImportance());
                criteriaCopy.setCultureElementRating(criteria.getCultureElementRating().getInTransaction(newObjTran));

                newTemplate.addToCultureCriterias(criteriaCopy);
            }
            
        });
        
        return RedisplayResult.getInstance();
    }
}