package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.components.ParticipantInitialisationContext;
import oneit.email.ConfigurableArticleTemplateEmailer;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.RedisplayResult;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.InitialisationException;
import oneit.utils.MultiException;
import oneit.utils.StringUtils;
import performa.intercom.resources.User;
import performa.intercom.utils.IntercomUtils;
import performa.orm.CompanyUser;
import performa.utils.Utils;


public class SaveUserDetailsFP extends SaveFP 
{
    protected ConfigurableArticleTemplateEmailer  emailer;

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        CompanyUser         companyUser =   (CompanyUser) request.getAttribute("CompanyUser");
        SecUser             secUser     =   companyUser.getUser();     
        
        LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1,"In SaveUserDetailsFP saving CompanyUser : ", companyUser );
         
        SecUser             oldSecUser  = (SecUser) secUser.getEarliestBackup();

        if(oldSecUser != null)
        {
            if( !CollectionUtils.equals(oldSecUser.getEmail(), secUser.getEmail()))
            {
                if(!companyUser.isLoggedViaSocial()) //email changed for normal user
                {
                    if(companyUser.getConfirmPassword() == null)
                    {
                        submission.getRequest().setAttribute("EmailChanged", true);
                        return RedisplayResult.getInstance();
                    }
                    else
                    {
                        boolean validPassword   =   secUser.checkPassword(companyUser.getConfirmPassword());

                        if(!validPassword)
                        {
                            submission.getRequest().setAttribute("EmailChanged", false);
                            companyUser.setConfirmPassword(null);
                        }

                        BusinessObjectParser.assertFieldCondition(validPassword, companyUser, CompanyUser.FIELD_ConfirmPassword, "passwordNotMatch");

                        if(validPassword)
                        {
    //                        companyUser.setIsAccountVerified(Boolean.FALSE);
                            companyUser.setIsEmailChanged(Boolean.TRUE);

                            Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
                        }
                    }

//                    secUser.setEmail(secUser.getUserName());
                }
                else //email changed for social login
                {
                    //send email verification mail
                    LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1,"Sending email resetted mail", companyUser );

                    companyUser.setIsEmailChanged(Boolean.TRUE);

                    Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
                }
            }
            
            User    intercomUser    =   IntercomUtils.updateIntercomUser(secUser);
            
            if(intercomUser == null)
            {
                performa.intercom.resources.Company intercomCompany =   IntercomUtils.findOrCreateCompany(companyUser.getCompany());

                IntercomUtils.createIntercomUser(secUser, "Hiring Team", intercomCompany);
            }
        }
        
        return super.processForm(process, submission, params);
    }
    
        
    @Override
    protected Map validate(SubmissionDetails submission, MultiException exceptions) 
    {
        HttpServletRequest  request     =   submission.getRequest();
        CompanyUser         companyUser =   (CompanyUser) request.getAttribute("CompanyUser");
        SecUser             secUser     =   companyUser.getUser();
        
        if(!companyUser.isLoggedViaSocial())
        {
            BusinessObjectParser.assertFieldCondition(StringUtils.isEmailAddress(secUser.getUserName()), secUser, SecUser.FIELD_Email, "invalid", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getUserName(), companyUser), secUser, SecUser.FIELD_UserName, "emailExists", exceptions, true, request);
        }
        else
        {
            BusinessObjectParser.assertFieldCondition(!Utils.isCompanyUserEmailFound(secUser.getTransaction(), secUser.getEmail(), companyUser), secUser, SecUser.FIELD_Email, "emailExists", exceptions, true, request);
        }
        
        BusinessObjectParser.assertFieldCondition(secUser.getFirstName()!= null, secUser, SecUser.FIELD_FirstName, "mandatory", exceptions, true, request);
        BusinessObjectParser.assertFieldCondition(secUser.getLastName()!= null, secUser, SecUser.FIELD_LastName, "mandatory", exceptions, true, request);
        
        return super.validate(submission, exceptions);
    }
    
    
    @Override
    public void init(ParticipantInitialisationContext context) throws InitialisationException
    {
        super.init(context);
        
        emailer = (ConfigurableArticleTemplateEmailer) (context.getSingleChild("AccountVerificationEmailer"));
    }
}