package performa.ws;

import java.util.*;
import oneit.appservices.ws.*;
import oneit.appservices.ws.services.ORMUpdateJSONService;
import oneit.objstore.*;
import oneit.security.SecUser;
import oneit.utils.*;
import org.json.*;
import performa.orm.*;

/**
 *
 * @author chamathkalhara
 */
public class SaveWorkflowAsCopy extends ORMUpdateJSONService
{

    @Override
    public void processForm(JSONServiceRequest request, ObjectTransaction objTran, JSONObject result, MultiException exceptions, 
                                                Set<BaseBusinessClass> createdBBCs, Set<BaseBusinessClass> updatedBBCs) throws BusinessException, JSONException
    {
        List<WorkFlowTemplate>   createdWorkFlowTemplates       = WSUtils.filterBBCs(WorkFlowTemplate.REFERENCE_WorkFlowTemplate, createdBBCs);
        List<WorkFlowTemplate>   updatedWorkFlowTemplates       = WSUtils.filterBBCs(WorkFlowTemplate.REFERENCE_WorkFlowTemplate, updatedBBCs);
        List<WorkFlowTemplate>   allWorkFlowTemplates           = new ArrayList(createdWorkFlowTemplates);
        
        allWorkFlowTemplates.addAll(updatedWorkFlowTemplates);
        
        for (WorkFlowTemplate workFlowTemplate : allWorkFlowTemplates)
        {
            WorkFlowTemplate cloanedTemplate = revertAttributesAndClone(workFlowTemplate);
            
            SecUser secUser =   SecUser.getTXUser(objTran);
        
            if(secUser != null && secUser.getExtension(CompanyUser.REFERENCE_CompanyUser) != null)
            {
                CompanyUser companyUser =   secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);

                cloanedTemplate.setHiringTeam(companyUser.getSelectedTeam());
            }
        }
        
        super.processForm(request, objTran, result, exceptions, createdBBCs, updatedBBCs); //To change body of generated methods, choose Tools | Templates.
    }
    
    private WorkFlowTemplate revertAttributesAndClone(WorkFlowTemplate workflowTemplate)
    {
        BaseBusinessClass[]         involvedObjs    = workflowTemplate.getTransaction().getObjectsToStore();
        WorkFlowTemplate            clonedTemplate  = workflowTemplate.getClonedTemplate();
        
        // Now we copy back the changed objects before cloning
        for (int i = 0; i < involvedObjs.length; i++)
        {
            if (involvedObjs[i].getStatus() == ObjectStatus.INVALID || involvedObjs[i].getStatus() == ObjectStatus.CLEAN)
            {
                // Do nothing
            }
            else if (involvedObjs[i].getStatus() == ObjectStatus.NEW)
            {
                involvedObjs[i].delete();
            }
            else
            {
                involvedObjs[i].rollback();
            }
        }
        
        return clonedTemplate;
    }
}