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.ObjectTransaction;
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.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(!companyUser.isLoggedViaSocial() && !CollectionUtils.equals(oldSecUser.getUserName(), secUser.getUserName()))
            {
                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);

                        Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
                    }
                }
            }
            else if (companyUser.isLoggedViaSocial() && !CollectionUtils.equals(oldSecUser.getEmail(), secUser.getEmail()))
            {
                //send email verification mail
                LogMgr.log(CompanyUser.LOG, LogLevel.PROCESSING1,"Sending email resetted mail", companyUser );
                
                Utils.sendEmailChangedMail(companyUser, request, emailer, SaveUserDetailsFP.class.getName());
                
                companyUser.setIsAccountVerified(Boolean.FALSE);
            }
        }
        
        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(!isCompanyUserEmailFound(secUser.getTransaction(), secUser.getUserName(), companyUser), secUser, SecUser.FIELD_UserName, "emailExists", exceptions, true, request);
        }
        else
        {
            BusinessObjectParser.assertFieldCondition(!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"));
    }
    

    private static Boolean isCompanyUserEmailFound(ObjectTransaction objTran, String email, CompanyUser currentUser)
    {
        if(email!=null)
        {
            SecUser user    = SecUser.searchNAME(objTran, email.toLowerCase());

            if(user!=null)
            {
                CompanyUser comUser = user.getExtension(CompanyUser.REFERENCE_CompanyUser); 
                
                if(comUser!=null && !CollectionUtils.equals(comUser, currentUser))
                {
                    return Boolean.TRUE;
                }
            }
        }

        return Boolean.FALSE;
    }
}