package info.bukova.isspst.ui.requirement;

import info.bukova.isspst.data.TripBill;
import info.bukova.isspst.data.TripRequirement;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.filters.TripRequirementFilter;
import info.bukova.isspst.services.requirement.TripRequirementService;
import info.bukova.isspst.services.tripbill.TripBillService;
import info.bukova.isspst.services.workgroups.WorkgroupService;
import org.springframework.security.access.AccessDeniedException;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Window;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TripRequirementListWorkgroup extends RequirementSubpage<TripRequirement> {
	
	@WireVariable
	private TripRequirementService tripRequirementService;

	@WireVariable
	private WorkgroupService workgroupService;

	@WireVariable
	private TripBillService tripBillService;

	private List<Workgroup> myCentres;

	private List<Workgroup> myWorkgroups;

	@Init(superclass = true)
	public void init() {
		service = tripRequirementService;
		dataClass = TripRequirement.class;
		formZul = "requirementsForm.zul";
		dataFilter = new TripRequirementFilter(getFilterTemplate());
		
		myCentres = workgroupService.getUserCentres(userService.getCurrent());
		myWorkgroups = workgroupService.getUserWorkgroups(userService.getCurrent());
	}

	@Override
	protected List<TripRequirement> getListFromService() {
		try {
			return tripRequirementService.getWorkgroupReq();
		} catch (AccessDeniedException e) {
			BindUtils.postGlobalCommand(null, null, "disableWorkgroup", null);
			return new ArrayList<TripRequirement>();
		}
	}

	public List<Workgroup> getMyCentres() {
		return myCentres;
	}

	public List<Workgroup> getMyWorkgroups() {
		return myWorkgroups;
	}

	@GlobalCommand
	@NotifyChange({ "dataList", "dataBean", "fullFill" })
	public void reloadRelated() {
		this.reload();
	}
	
	@Override
	protected void beforeSelectViaUrl() {
		BindUtils.postGlobalCommand(null, null, "selectWorkgroup", null);
	}

	@Command
	public void showTripBill() {
		if (getDataBean() == null) {
			return;
		}

		TripBill tb = tripRequirementService.getTripBill(getDataBean());
		tripBillService.loadLazyData(tb);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("bill", tb);
		Window win = (Window) Executions.createComponents("tripBillSummaryMaster.zul", null, params);
		win.doModal();
	}

}
