/*
 * 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.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
import javax.inject.Inject;
import javax.inject.Named;
import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition;
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition;
import javax.security.enterprise.identitystore.IdentityStore;
import javax.security.enterprise.identitystore.Pbkdf2PasswordHash;
import org.apache.log4j.Logger;
import plate.wellmann.shop.business.MyPasswordHash;
/**
 *
 * @author Patrick
 */
/*@AutoApplySession // For "Is user already logged-in?"
@RememberMe(isRememberMeExpression = "httpMessageContext.authParameters.rememberMe", cookieMaxAgeSeconds = 60 * 60 * 24 * 14) // 14 days*/
@CustomFormAuthenticationMechanismDefinition(
  loginToContinue = @LoginToContinue(
    loginPage = "/login.xhtml",
    useForwardToLogin = false,
    errorPage = "/error.xhtml"
        ))
@DatabaseIdentityStoreDefinition(
    dataSourceLookup = "${'java:/Wellmann-Shop'}",
    callerQuery = "#{'select password from Password where customer_id = (select id from customer where Email = ?)'}",
    groupsQuery = "select userGroup from MyUserGroups where customer_id = (select id from customer where Email = ?)",
    hashAlgorithm = MyPasswordHash.class,
    priority = 10
        )
@FacesConfig
@ApplicationScoped
@Named
public class ApplicationConfig {
    
    final static Logger logger = Logger.getLogger(ApplicationConfig.class);
    
    @Inject
    private IdentityStore identityStore;
    
    @Inject
    private Pbkdf2PasswordHash passwordHash;
    
    /*@Inject
    private EntityManager em;*/
    
    /*@Transactional
    private void init(){
        PasswordManager passwordManager = new PasswordManager();
        Salt salt = new Salt();
        byte[] password = passwordManager.hashPassword("user".toCharArray(), salt.getSalt(), salt.getInterations());
        Customer test = new Customer("user@test.de", password, salt);
        test.setGroups(new MyUserGroups(test, MyUserGroups.Group.ADMIN));
        try {
            em.persist(test);
            logger.debug(test.getEmail() + " got registered");
        } catch (Exception e) {
            logger.error("Init persisting doenst work : " + e.toString());
        }
    }*/
    
    /*
    public AuthenticationStatus validateRequest(
            HttpServletRequest request, 
            HttpServletResponse response, 
            HttpMessageContext context) throws AuthenticationException {
        
        Credential credential = context.getAuthParameters().getCredential();

        if (credential != null) {
            return context.notifyContainerAboutLogin(identityStore.validate(credential));
        } else {
            return context.doNothing();
        }
    }*/
    
    public String hashPw(String pw){
        return passwordHash.generate(pw.toCharArray());
    }
}
