package performa.ws;

import java.util.Set;
import oneit.appservices.ws.JSONServiceRequest;
import oneit.business.content.Article;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.BaseBusinessClass;
import oneit.objstore.ObjectTransaction;
import oneit.utils.*;
import org.json.JSONException;
import org.json.JSONObject;
import performa.orm.HiringTeam;
import performa.orm.types.RoleType;
import performa.utils.WebUtils;


public class CreateJobVisibilityFP extends BaseCreateJobVisibilityFP
{
    private static final long serialVersionUID  =   0L;
    public static LoggingArea LOG               =   LoggingArea.createLoggingArea("CreateJobVisibilityFP");
    
    // This constructor should not be called
    public CreateJobVisibilityFP ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }
    
    @Override
    public void processForm(JSONServiceRequest request, ObjectTransaction objTran, JSONObject result, MultiException exceptions, 
                                                Set<BaseBusinessClass> createdBBCs, Set<BaseBusinessClass> updatedBBCs) throws BusinessException, JSONException
    {
        HiringTeam  selectedTeam    =   getSelectedTeam();
                            
        LogMgr.log(LOG, LogLevel.PROCESSING1, "Checking Create Job Visibility. Selected Team: ", selectedTeam , " Company User: " , getCompanyUser());

        if(getCompanyUser() != null && selectedTeam != null)
        {
            boolean canCreateJob    =   selectedTeam.allowJobCreation();
            boolean trialNotAllowed =   selectedTeam.trialJobNotAllowed();
            String  redirectURL;
            
            result.put("AllowCreateJob", canCreateJob ? "SUCCESS" : trialNotAllowed ? "TRIAL" : "REACHED_CAP");

            if (!canCreateJob)
            {
                Article companyArticle  =   WebUtils.getArticleByShortCut(objTran, WebUtils.MY_COMPANY);
                
                redirectURL =   companyArticle.getLink(request.getRequest(), CollectionUtils.mapEntry("cms.rm", selectedTeam.getCardID() == null ? "Billing" : "ManagePlan").toMap());
                
                result.put("StandardUser", getCompanyUser().getRoleForHiringTeam(selectedTeam) == RoleType.STANDARD);
            }
            else
            {
                Article jobsArticle =   WebUtils.getArticleByShortCut(objTran, WebUtils.JOBS);
                
                redirectURL =   jobsArticle.getLink(request.getRequest(), CollectionUtils.mapEntry("cms.rm", WebUtils.START_JOB).toMap());
            }
            result.put("redirectURL", redirectURL);
            LogMgr.log(LOG, LogLevel.PROCESSING1, "Can Create Job : " , canCreateJob , " Trial Not Allowed: ", trialNotAllowed);
            
        }
    }
}