package com.braintree.auth;


import de.hybris.platform.core.Registry;
import de.hybris.platform.core.model.user.CustomerModel;
import de.hybris.platform.core.model.user.UserModel;
import de.hybris.platform.jalo.JaloConnection;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.jalo.user.User;
import de.hybris.platform.jalo.user.UserManager;
import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
import de.hybris.platform.servicelayer.user.UserService;
import de.hybris.platform.spring.security.CoreAuthenticationProvider;
import de.hybris.platform.spring.security.CoreUserDetails;
import java.util.Collections;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class PayPalAuthProvider extends CoreAuthenticationProvider {

    private static final String NONE_PROVIDED = "NONE_PROVIDED";
    private static final String CORE_AUTHENTICATION_PROVIDER_BAD_CREDENTIALS = "CoreAuthenticationProvider.badCredentials";
    private static final String BAD_CREDENTIALS = "Bad credentials";
    private static final String SYSTEM_NOT_INITIALIZED = "systemNotInitialized";
    private final UserDetailsChecker postAuthenticationChecks = new PayPalAuthProvider.DefaultPostAuthenticationChecks();
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (this.hasCurrentTenant() && this.isSystemInitialized()) {
            try {
                UserDetails userDetails = null;
                String userName = authentication.getPrincipal() == null ? NONE_PROVIDED : authentication.getName();
                UserModel userForUID = userService.getUserForUID(userName);
                if (userForUID instanceof CustomerModel) {
                    CustomerModel customer = (CustomerModel) userForUID;
                    if (StringUtils.isNotBlank(customer.getPayPalAccessToken())) {
                        userDetails = this.retrieveUser(userName);
                        this.getPreAuthenticationChecks().check(userDetails);
                        User user = getUserManagerInstance(userDetails.getUsername());
                        Object credential = authentication.getCredentials();
                        verifyCredential(credential, customer);

                        this.additionalAuthenticationChecks(userDetails, (AbstractAuthenticationToken) authentication);
                        this.postAuthenticationChecks.check(userDetails);
                        setUserToCurrentSession(user);
                        return this.createSuccessAuthentication(authentication, userDetails);
                    } else {
                        return super.authenticate(authentication);
                    }
                } else {
                    return super.authenticate(authentication);
                }
            } catch (UsernameNotFoundException | UnknownIdentifierException var6) {
                throw new BadCredentialsException(
                    this.messages.getMessage(CORE_AUTHENTICATION_PROVIDER_BAD_CREDENTIALS, BAD_CREDENTIALS), var6);
            }
        } else {
            return this.createSuccessAuthentication(authentication, new CoreUserDetails(SYSTEM_NOT_INITIALIZED, SYSTEM_NOT_INITIALIZED, true, false, true, true, Collections.emptyList(), (String)null));
        }

    }

    private void verifyCredential(Object credential, CustomerModel customer) {
        if (credential instanceof String) {
            if (!customer.getPayPalAccessToken().equals(credential)) {
                throw new BadCredentialsException(
                        this.messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        } else {
            throw new BadCredentialsException(this.messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    private class DefaultPostAuthenticationChecks implements UserDetailsChecker {
        private DefaultPostAuthenticationChecks() {
        }

        public void check(UserDetails user) {
            if (!user.isCredentialsNonExpired()) {
                throw new CredentialsExpiredException(PayPalAuthProvider.this.messages.getMessage("CoreAuthenticationProvider.credentialsExpired", "User credentials have expired"));
            }
        }
    }

    @Override
    protected Authentication createSuccessAuthentication(Authentication authentication, UserDetails user) {
        ConnectWithPayPalAuthenticationToken result = new ConnectWithPayPalAuthenticationToken(user.getUsername(),
            user.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    protected boolean hasCurrentTenant() {
        return Registry.hasCurrentTenant();
    }

    protected boolean isSystemInitialized() {
        return JaloConnection.getInstance().isSystemInitialized();
    }

    protected User getUserManagerInstance(String userName) {
        return UserManager.getInstance().getUserByLogin(userName);
    }

    protected void setUserToCurrentSession(User user) {
        JaloSession.getCurrentSession().setUser(user);
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
