package com.itsol.quantrivanphong.manager.employee.business.impl;

import com.itsol.quantrivanphong.manager.employee.business.EmployeeBusiness;
import com.itsol.quantrivanphong.manager.employee.repository.EmployeeRepository;
import com.itsol.quantrivanphong.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;

import java.util.List;

@Service
public class EmployeeBusinessImpl implements EmployeeBusiness {
    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public List<Employee> findAll() {
        return employeeRepository.findAll();
    }

    @Override
    public Employee findById(int id) {
        return employeeRepository.findById(id).orElse(null);
    }

    @Override
    public Employee findEmployeeByEmailAddress(String email) {
        return employeeRepository.findEmployeeByEmailAddress(email);
    }

    @Override
    public Employee findEmployeeByUserName(String name) {
        return employeeRepository.findEmployeeByUsername(name);
    }

    @Override
    public Employee findEmployeeByUsernameAndPassword(String username, String password) {
        return employeeRepository.findEmployeeByUsernameAndPassword(username,password);
    }

    @Override
    public void save(Employee employee) {
      employeeRepository.save(employee);
    }

    @Override
    public void deleteById( int id) {
      employeeRepository.deleteById(id);
    }

    @Override
    public boolean confirmEmployee(Employee employee) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return Employee.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Employee employee = (Employee) target;
        if(employeeRepository.findEmployeeByUsername(employee.getUsername())!=null){
            errors.rejectValue("username","username.alreadyExist");
        }

        if(employeeRepository.findEmployeeByEmailAddress(employee.getEmailAddress())!=null){
            errors.rejectValue("email","email.alreadyExist");
        }

        if(!employee.getPassword().equals(employee.getConfirmPassword())){
            errors.rejectValue("password","password.wrongPassword");
        }

    }
}
