package org.academiadecodigo.bootcamp.fxlogin.service.user;

import org.academiadecodigo.bootcamp.fxlogin.model.User;
import org.academiadecodigo.bootcamp.fxlogin.persistence.TransactionException;
import org.academiadecodigo.bootcamp.fxlogin.persistence.dao.UserDao;
import org.academiadecodigo.bootcamp.fxlogin.persistence.dao.jpa.JpaUserDao;
import org.academiadecodigo.bootcamp.fxlogin.utils.Security;
import org.springframework.transaction.annotation.Transactional;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserServiceImpl(JpaUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public boolean authenticate(String username, String password) {
        boolean result = false;
        User user = userDao.findByUsername(username);

        if (user != null) {
            result = user.getPassword().equals(Security.getHashed(password));
        }

        return result;
    }

    @Transactional(readOnly = false, rollbackFor = TransactionException.class)
    @Override
    public void addUser(User user) throws TransactionException {
        if (userDao.findByUsername(user.getUsername()) == null) {
            userDao.saveOrUpdate(user);
        }
    }

    @Override
    public User findByName(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public Long count() {
        return userDao.count();
    }
}
