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 oneit.utils.parsers.FieldException;
import performa.orm.*;

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

    @Override
    public void processForm(JSONServiceRequest request, ObjectTransaction objTran, org.json.JSONObject result, MultiException exceptions, 
                                            Set<BaseBusinessClass> createdBBCs, Set<BaseBusinessClass> updatedBBCs) throws BusinessException, org.json.JSONException, FieldException
    {
        List<MessageTemplate>   createdMessageTemplates       = WSUtils.filterBBCs(MessageTemplate.REFERENCE_MessageTemplate, createdBBCs);
        List<MessageTemplate>   updatedMessageTemplates       = WSUtils.filterBBCs(MessageTemplate.REFERENCE_MessageTemplate, updatedBBCs);
        List<MessageTemplate>   allMessageTemplates           = new ArrayList(createdMessageTemplates);
        
        allMessageTemplates.addAll(updatedMessageTemplates);
        
        for (MessageTemplate messageTemplate : allMessageTemplates)
        {
            MessageTemplate cloanedTemplate = revertAttributesAndClone(messageTemplate);
            
            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);
    }
    
    private MessageTemplate revertAttributesAndClone(MessageTemplate messageTemplate)
    {
        BaseBusinessClass[]         involvedObjs    = messageTemplate.getTransaction().getObjectsToStore();
        MessageTemplate             clonedTemplate  = messageTemplate.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;
    }
}