/*
 * Copyright 2018 JoinFaces.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package httpauthenticationmechanism;

import java.io.IOException;
import java.util.Arrays;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Model;
import javax.faces.application.FacesMessage;
import static javax.faces.application.FacesMessage.SEVERITY_ERROR;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.security.enterprise.AuthenticationStatus;
import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE;
import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE;
import javax.security.enterprise.SecurityContext;
import javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters;
import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams;
import javax.security.enterprise.credential.Credential;
import javax.security.enterprise.credential.Password;
import javax.security.enterprise.credential.UsernamePasswordCredential;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.IdentityStoreHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.log4j.Logger;
import plate.wellmann.shop.business.PasswordManager;
import plate.wellmann.shop.persistence.Customer;
import plate.wellmann.shop.persistence.MyUserGroups;
import plate.wellmann.shop.persistence.Salt;

/**
 *
 * @author Patrick
 */
@Named
@RequestScoped
public class LoginBean {
    
    @Inject
    private PasswordManager passwordManager;

    @Inject
    private IdentityStoreHandler identityStoreHandler;

    @Inject
    private SecurityContext securityContext;

    @Inject
    private FacesContext facesContext;

    @Inject
    private ExternalContext externalContext;

    @NotEmpty
    @Email(message = "Please provide a valid email")
    private String username;

    @NotEmpty
    @Size(min = 4, max = 50, message = "Password must be between 4 and 50 characters")
    private String password;

    private boolean rememberMe = false;

    private boolean continued = true;

    final static Logger LOG = Logger.getLogger(LoginBean.class);

    public void login() throws IOException {
        Credential credential = new UsernamePasswordCredential(username, new Password(password));

        CredentialValidationResult cres = identityStoreHandler.validate(credential);
        switch (cres.getStatus()) {
            case VALID:
                facesContext.responseComplete();
                facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Anmeldung erfolgreich!", null));
                break;
            default:
                facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Benutzername oder Password inkorrekt!", null));
                break;

        }

        /*
        switch (continueAuthentication()) {
            case SEND_CONTINUE:
                facesContext.responseComplete();
                break;
            case SEND_FAILURE:
                facesContext.addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed", null));
                break;
            case SUCCESS:
                facesContext.addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO, "Login succeed", null));
                externalContext.redirect(externalContext.getRequestContextPath() + "/ressources/users/welcome.xhtml");
                break;
            case NOT_DONE:
        }*/
    }

    private static HttpServletResponse getResponse(FacesContext facesContext) {
        return (HttpServletResponse) facesContext
                .getExternalContext()
                .getResponse();
    }

    private static HttpServletRequest getRequest(FacesContext facesContext) {
        return (HttpServletRequest) facesContext
                .getExternalContext()
                .getRequest();
    }

    private AuthenticationStatus continueAuthentication() {
        return securityContext.authenticate(
                (HttpServletRequest) externalContext.getRequest(),
                (HttpServletResponse) externalContext.getResponse(),
                AuthenticationParameters.withParams()
                .credential(new UsernamePasswordCredential(username, password))
        );
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isRememberMe() {
        return rememberMe;
    }

    public void setRememberMe(boolean rememberMe) {
        this.rememberMe = rememberMe;
    }

    public boolean isContinued() {
        return continued;
    }

    public void setContinued(boolean continued) {
        this.continued = continued;
    }

}
