package info.bukova.isspst.services.limits;

import info.bukova.isspst.data.Limit;
import info.bukova.isspst.data.Season;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.services.AbstractOwnedService;
import info.bukova.isspst.services.settings.SeasonService;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Pepa Rokos
 */
public class LimitServiceImpl extends AbstractOwnedService<Limit> implements LimitService {

	@Autowired
	private SeasonService seasonService;

	@Override
	@Transactional
	public List<Limit> getForSeason(Season season) {
		Query q = dao.getQuery("from Limit where season = :season");
		q.setParameter("season", season);
		return q.list();
	}

	@Override
	@Transactional
	public Limit getForWorkgroupAndSeason(Workgroup wg, Season season) {
		Query q = dao.getQuery("from Limit where workgroup = :wg and season = :season");
		q.setParameter("wg", wg);
		q.setParameter("season", season);
		return (Limit) q.uniqueResult();
	}

	@Override
	@Transactional
	public Limit getForWorkgroup(Workgroup wg) {
		return getForWorkgroupAndSeason(wg, seasonService.getActive());
	}

	@Override
	@Transactional
	@PreAuthorize("hasPermission(this, 'PERM_ADD')")
	public void add(Limit entity) {
		if (getForWorkgroupAndSeason(entity.getWorkgroup(),entity.getSeason()) != null) {
			throw new LimitException("LimitExists");
		}
		super.add(entity);
	}

	@Override
	protected Limit createEntity() {
		Limit limit = new Limit();
		limit.setSeason(seasonService.getActive());
		return limit;
	}
}
