package performa.orm;

import oneit.logging.LoggingArea;
import oneit.objstore.*;
import oneit.security.SecUser;
import oneit.security.jsp.SecUserToNameTransform;
import oneit.utils.*;
import oneit.utils.parsers.FieldException;
import performa.orm.types.RoleType;
import performa.utils.Utils;


public class CompanyUser extends BaseCompanyUser
{
    private static final long serialVersionUID = 0L;
        
    public  static LoggingArea  LOG = LoggingArea.createLoggingArea("CompanyUser");

    // This constructor should not be called
    public CompanyUser ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }
    
    
    public static CompanyUser getCompanyUserForForgotPassword(ObjectTransaction transaction, String userIDStr, String code)
    {
        userIDStr   =   StringUtils.subBlanks(userIDStr);
        code        =   StringUtils.subBlanks(code);
        
        if(userIDStr != null && code!=null)
        {
            CompanyUser companyUser =   CompanyUser.getCompanyUserByID(transaction, Long.parseLong(userIDStr));
                        
            if(companyUser != null && CollectionUtils.equals(companyUser.getForgotPasswordKey(), code))
            {
                return companyUser;
            }
        }
        
        return null;
    }

    
    @Override
    public String getToString() 
    {
        return SecUserToNameTransform.INSTANCE.transform(getUser());
    }

    
    @Override
    protected void postRoleChange() throws FieldException 
    {
        SecUser secUser =   getUser();
        
        if(getRole()==RoleType.ADMIN)
        {
            if(secUser.hasRole(Utils.ROLE_COMPANY_USER))
            {
                secUser.removeRole(Utils.getRole(Utils.ROLE_COMPANY_USER, getTransaction()));
            }
            
            secUser.addRole(Utils.getRole(Utils.ROLE_COMPANY_ADMIN, getTransaction()));
        }
        else if(getRole()==RoleType.STANDARD)
        {
            if(secUser.hasRole(Utils.ROLE_COMPANY_ADMIN))
            {
                secUser.removeRole(Utils.getRole(Utils.ROLE_COMPANY_ADMIN, getTransaction()));
            }
            
            secUser.addRole(Utils.getRole(Utils.ROLE_COMPANY_USER, getTransaction()));
        }
        
        super.postRoleChange();
    }

    
    @Override
    public FieldWriteability getWriteability_Role() 
    {
        if(CollectionUtils.equals(getCompany().getAddedByUser(),this))
        {
            return FieldWriteability.NOT_IN_GUI;
        }
        
        return super.getWriteability_Role();
    }
}