package com.nisum.mongodb.service;

import com.nisum.mongodb.model.Employee;
import com.nisum.mongodb.repository.EmployeeListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Optional;

@Service
public class EmployeeListService {

    @Autowired
    EmployeeListRepository employeeListRepository;

    public List<Employee> findAllEmployees() {
        return employeeListRepository.findAll();
    }

    public Employee addEmployee(Employee employee) {
        return employeeListRepository.save(employee);
    }

    public Optional<Employee> getEmployeeById(Long employeeId) {
        return employeeListRepository.findById(employeeId);
    }

    public void deleteEmployee(Long employeeId){
        Optional<Employee> employee = getEmployeeById(employeeId);
        System.out.println("emp frm getEmployeeById: deleteEmployee"+ employee);
        if(employee.isPresent()){
            System.out.println("EmployeeListService:deleteEmployee(): Employee is available to be deleted:");
            employeeListRepository.deleteById(employeeId);
        }else{
            System.out.println("EmployeeListService:deleteEmployee(): Employee is not available to be deleted:");
        }
    }

    public Employee updateEmployee(Long employeeId, Employee updatedEmp){
        Optional<Employee> employee = getEmployeeById(employeeId);
        //Employee emp = employee.isPresent() ? updatedEmp : new Employee();
        System.out.println("emp : updateEmployee"+ employee.isPresent());

        if(employee.isPresent()){
            System.out.println("EmployeeListService:updateEmployee(),emp is available to update:");
            updatedEmp.setId(employeeId);
            return employeeListRepository.save(updatedEmp);
        }else{
            System.out.println("EmployeeListService:updateEmployee() Employee is not available to update:");
        }
        return updatedEmp;

    }

    /*public ResponseEntity<Employee> updateEmployee(Long employeeId, Employee updatedEmp){
        //Optional<Employee> employee = getEmployeeById(employeeId);
        Employee e =  employeeListRepository.getById(employeeId);
        System.out.println("Employee: updateEmployee:" + e);
        if(e == null){
            System.out.println("Emp not found to update for the id:" + employeeId);
            e = new Employee();
           return  ResponseEntity.notFound().build();
        }
        else{
            System.out.println("inside");
            e.setName(updatedEmp.getName());
            e.setAge(updatedEmp.getAge());
            employeeListRepository.save(e);
            System.out.println("after save");
            return ResponseEntity.ok(e);
        }

    }*/

}
