package com.nisum.dao.impl;

import com.nisum.dao.Dao;
import com.nisum.model.impl.EmployeeImp;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Collection;
import java.util.Optional;

@Repository
@Qualifier("EmployeeDao")
@Transactional
public class EmployeeDao implements Dao<EmployeeImp> {

  @PersistenceContext
  private EntityManager entityManager;

  @Override
  public Optional<EmployeeImp> getById(int id) {
    return Optional.of(entityManager.find(EmployeeImp.class, id));
  }

  @Override
  public Collection<EmployeeImp> getAll() {
    TypedQuery<EmployeeImp> typedQuery = entityManager.createQuery("SELECT e FROM employee e", EmployeeImp.class);
    return typedQuery.getResultList();
  }

  @Override
  public void save(EmployeeImp employeeImp) {
        entityManager.persist(employeeImp);
  }

  @Override
  public void update(EmployeeImp employeeImp) {

  }

  @Override
  public void delete(EmployeeImp employeeImp) {
    entityManager.remove(entityManager.contains(employeeImp) ? employeeImp : entityManager.merge(employeeImp));
  }
}
