package info.bukova.isspst.services.signeddocs;

import info.bukova.isspst.Module;
import info.bukova.isspst.ModuleUtils;
import info.bukova.isspst.data.DataModel;
import info.bukova.isspst.data.SignedDocument;
import info.bukova.isspst.data.SignedDocumentItem;
import info.bukova.isspst.services.AbstractOwnedService;
import info.bukova.isspst.services.LazyLoader;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;

public class SignedDocumentServiceImpl extends AbstractOwnedService<SignedDocument> implements SignedDocumentService {

	@Autowired
	private ServletContext servletContext;

	@LazyLoader("grid")
	@Transactional
	public void lazyLoadItems(SignedDocument signedDocument) {
		if (signedDocument == null) {
			return;
		}

		SignedDocument sd = dao.getById(signedDocument.getId());
		Hibernate.initialize(sd.getItems());
		signedDocument.setItems(sd.getItems());
	}

	@Override
	@Transactional
	public SignedDocument getForEntity(DataModel entity) {
		Module module = ModuleUtils.getModule(entity, servletContext);

		if (module == null) {
			return null;
		}

		Query q = dao.getQuery("from SignedDocument where moduleName = :module and recordId = :record");
		q.setParameter("module", module.getId());
		q.setParameter("record", entity.getId());

		return (SignedDocument) q.uniqueResult();
	}

	@Override
	@Transactional
	public SignedDocumentItem getItem(DataModel entity, long reportId) {
		SignedDocument doc = getForEntity(entity);

		if (doc == null) {
			return null;
		}

		for (SignedDocumentItem item : doc.getItems()) {
			if (item.getReportId() == reportId) {
				return item;
			}
		}

		return null;
	}

	@Override
	public void addFromApprove(SignedDocument document) {
		super.add(document);
	}


}
