package performa.orm;

import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import oneit.objstore.MessageSource;
import oneit.objstore.ObjectTransaction;
import oneit.servlets.objstore.MessageSourceDecorator;
import oneit.servlets.process.ORMProcessState;
import oneit.utils.CollectionUtils;
import oneit.utils.DateDiff;
import oneit.utils.StringUtils;


public class Candidate extends BaseCandidate
{
    private static final long serialVersionUID = 0L;
    
    // This constructor should not be called
    public Candidate ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }
    
    
    public String getFirstName()
    {
        return getUser() != null ? getUser().getFirstName() : null;
    }

    
    @Override
    public String getToString() 
    {
        return getUser() != null ? getUser().getName() : null;
    }   

    
    public static String checkCandidate(HttpServletRequest request, ORMProcessState process)
    {
        ObjectTransaction   transaction         =   process.getTransaction();
        String              candidateID         =   (String) request.getParameter("id");
        String              verificationCode    =   (String) request.getParameter("pin");
        MessageSource       messageSource       =   MessageSourceDecorator.getMessageSource(request);
        Candidate           candidate           =   null;
        String              errorMsg            =   "";
        
        if(StringUtils.subBlanks(candidateID) != null && StringUtils.subBlanks(verificationCode) != null)
        {
            candidate = Candidate.getCandidateByID(transaction, Long.parseLong(candidateID));
            
            process.setAttribute("Candidate", candidate);
        }
        else if(process.getAttribute("Candidate") != null)
        {
            candidate = (Candidate) process.getAttribute("Candidate");
        }
        else
        {
            errorMsg = messageSource.getFieldErrorMsg(Candidate.REFERENCE_Candidate, "", "UnauthorizedUser", null);
        }

        if(candidate == null)
        {
            errorMsg = messageSource.getFieldErrorMsg(Candidate.REFERENCE_Candidate, "", "UnauthorizedUser", null);
        }
        else if(!CollectionUtils.equals(verificationCode, candidate.getVerificationKey()))
        {
            errorMsg = messageSource.getFieldErrorMsg(Candidate.REFERENCE_Candidate, "", "WrongVerificationCode", null);
        }
        else if(DateDiff.getDateDiff(Calendar.HOUR, candidate.getVerificationMailSendDate(), new Date()) > 24)
        {
            errorMsg = messageSource.getFieldErrorMsg(Candidate.REFERENCE_Candidate, "", "LinkExpired", null);
        }
        
        return errorMsg;
    }
}