/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.triz.trizservice.security.impl;


import com.triz.trizservice.modeles.ServiceMember;
import com.triz.trizservice.modeles.ServiceUser;
import com.triz.trizservice.service.TransactionService;
import com.triz.util.UtilContext;
import com.triz.util.UtilURL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;

/**
 * this service provide authentification
 *
 * @author kamel.ider
 */
@Service("loginService")
@Component("loginService")
public class LoginServiceImpl implements AuthenticationProvider {

    private static boolean enabled = true;
    private static boolean accountNonExpired = true;
    private static boolean credentialsNonExpired = true;
    private static boolean accountNonLocked = true;
    //@Resource(name = "transactionService")
    
    @Autowired
    private TransactionService transactionService;
    
    
    @Autowired
    public UtilContext context;

    
    private Timer timer;
    private Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
    
    @Autowired
    @Qualifier("dataSourceAuthenticationManager")
    private AuthenticationManager dataSourceAuthenticationManager;

    public LoginServiceImpl() {
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println("login ------");
        ServiceUser daoUser = null;
        //authentication=dataSourceAuthenticationManager.authenticate(authentication);
        String loginName = authentication.getName();
        System.out.println("loginName: " + loginName);
        daoUser = transactionService.getUserById(loginName.trim());
        System.out.println("daoUser: " + daoUser);
        UtilURL.showURL();
        if (daoUser == null) {
            throw new UsernameNotFoundException("Login erroné");
        } else if (!daoUser.getActif().contains("true")) {
            throw new UsernameNotFoundException("Votre compte est disactivé veuillez contacter l'administrateur");
        }

        try {
            String pwd = authentication.getCredentials().toString();
            System.out.println("pwd: " + pwd);
            
            if (login(daoUser, pwd)) {
                System.out.println("inside if: " + pwd);
                List<ServiceMember> groups = transactionService.getGroupsByUser(daoUser);
                Collection<GrantedAuthority> adminAuthorities = new ArrayList<GrantedAuthority>();
                adminAuthorities.add(new SimpleGrantedAuthority("ROLE_REGISTERED"));
                System.out.println("groups: " + groups.size());
                if (!groups.isEmpty()) {
                    for (ServiceMember group : groups) {
                        System.out.println("group: " + group.getFkGroupe());
                        adminAuthorities.add(new SimpleGrantedAuthority("ROLE_" + group.getFkGroupe().getId().toUpperCase()));
                    }
                }
                User user = new User(loginName.trim(), pwd.trim(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, adminAuthorities);

                return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), adminAuthorities);
            }
        } catch (Exception e) {
            System.out.println("error: " + e.getMessage());
            logger.error("", e);
            if (e.getCause() != null && e.getCause() instanceof java.net.ConnectException) {
                throw new UsernameNotFoundException("Le serveur n'est pas accessible veuillez verifier votre connexion ou contacter l'administrateur");
            }
        }
        if (daoUser != null) {
            //dataService.createHistoric(daoUser.getId(), HistoricAction.FAILLOGIN);
        }
        throw new UsernameNotFoundException("Mot de passe erroné");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    private boolean login(ServiceUser user, String pw) {
        System.out.println("pw: hh " + pw);
        System.out.println("user.getPw(): " + user.getUserpw()+"hh ");
        if (user.getUserpw().equals(pw)) {
            System.out.println("true");
            return true;
        }
            System.out.println("false");
        return false;
    }
}
