package info.bukova.isspst.services.orders;

import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.data.JoinedItem;
import info.bukova.isspst.data.RequirementItem;
import info.bukova.isspst.data.RequirementState;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.reporting.Report;
import info.bukova.isspst.reporting.ReportType;
import info.bukova.isspst.services.AbstractService;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.services.workgroups.WorkgroupService;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;

public class ApprovedServiceImpl extends AbstractService<JoinedItem> implements ApprovedService
{
	@Autowired
	WorkgroupService workgroupService;

	@Autowired
	UserService userService;

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	@PreAuthorize("hasPermission(this, 'PERM_SHOW_CENTRE_REQ')")
	@PostFilter("hasPermission(filterObject, 'PERM_SHOW_CENTRE_REQ')")
	public List<JoinedItem> getAll()
	{
		List<Workgroup> wgList = workgroupService.getUserCentres(userService.getCurrent());
		Query q = queryDao.getQuery("select item "
				+ "from RequirementItem item left join item.requirement rq join rq.centre c "
				+ "where rq.kind is not null "
				+ "and rq.state = :state "
				+ "and (rq.project Is Null or rq.project = false) "
				+ "and c in (:wgList) "
				+ "and (item.orderNum Is Null or item.orderNum = '')");
		q.setParameterList("wgList", wgList);
		q.setParameter("state", RequirementState.APPROVED);
		List<JoinedItem> items = new ArrayList<JoinedItem>();

		for (RequirementItem it : (List<RequirementItem>) q.list())
		{
			// Kvůli lazy loadu načteme jakoukoli hodnotu objektu
			Hibernate.initialize(it.getRequirement().getOwnedBy());

			items.add(new JoinedItem(it, it.getRequirement().getWorkgroup(), it.getRequirement().getCentre(), it.getRequirement().getOwnedBy()));
		}

		return items;
	}

	@Override
	public Module getModule() {
		for (Module m : Constants.MODULES) {
			if (m.getId() == Constants.MOD_REQUIREMENTS) {
				return m;
			}
		}
		
		return null;
	}

	@Override
	public List<Report> getReports() {
		Report rep = new Report();
		rep.setType(ReportType.DYNAMIC);
		rep.setName(Constants.DYNAMIC_REPORT_NAME);
		
		List<Report> ret = new ArrayList<Report>();
		ret.add(rep);
		
		return ret;
	}
}
