package ovh.herisson.Clyde.Services;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import ovh.herisson.Clyde.Repositories.UserRepository;
import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.User;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepo;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public UserService(UserRepository userRepo){
        this.userRepo = userRepo;
    }


    public User getUser(String identifier){
        if (identifier == null) return null;
        try {
            int id = Integer.parseInt(identifier);
            return userRepo.findById(id);
        }
        catch (NumberFormatException nfe){
            return userRepo.findByEmail(identifier);
        }
    }


    public boolean checkPassword(User user, String tryingPassword){
        return passwordEncoder.matches(tryingPassword,  user.getPassword());
    }

    public void save(User  user){
        userRepo.save(user);
    }

    public Iterable<User> getAll(){
        return userRepo.findAll();
    }

}