package ru.ulstu.is.cbapp.service;

import ru.ulstu.is.cbapp.models.Category;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CategoryService {
    @PersistenceContext
    private EntityManager em;

    @Transactional
    public Category addCategory(String name) {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Student's data is null or empty");
        }
        final Category category = new Category(name);
        em.persist(category);
        return category;
    }

    @Transactional
    public Category findCategory(Long id) {
        final Category category = em.find(Category.class, id);
        if (category == null) {
            throw new EntityNotFoundException(String.format("Category with id [%s] is not found", id));
        }
        return category;
    }

    @Transactional(readOnly = true)
    public List<Category> findAllCategories() {
        return em.createQuery("select p from Category p", Category.class)
                .getResultList();
    }

    @Transactional
    public Category updateCategory(Long id, String surname, String name, String phoneNumber) {
        if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) {
            throw new IllegalArgumentException("Student's data is null or empty");
        }
        final Category currentCategory = findCategory(id);
        currentCategory.setName(name);

        return em.merge(currentCategory);
    }

    @Transactional
    public Category deleteCategory(Long id) {
        final Category p = findCategory(id);
        em.remove(p);
        return p;
    }

    @Transactional
    public void deleteAllCategories() {
        em.createQuery("delete from Category").executeUpdate();
    }


}
