package info.bukova.isspst.ui.tripbill;

import info.bukova.isspst.StringUtils;
import info.bukova.isspst.data.TripBill;
import info.bukova.isspst.services.tripbill.PayException;
import info.bukova.isspst.services.tripbill.TripBillService;
import info.bukova.isspst.ui.ListViewModel;
import org.springframework.security.access.AccessDeniedException;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import java.util.Date;

/**
 * @author Pepa Rokos
 */
public class PayDialogVM {

	@WireVariable
	private TripBillService tripBillService;
	private TripBill bill;
	private ListViewModel grid;
	private Date payDate;

	@Init
	public void init(@ExecutionArgParam("bill") TripBill bill,
					 @ExecutionArgParam("grid") ListViewModel grid) {
		this.bill = bill;
		this.grid = grid;
	}

	@Command
	public void pay(@BindingParam("window") Window window) {
		try {
			tripBillService.setPaid(bill, payDate);
			BindUtils.postNotifyChange(null, null, grid, "dataBean");
			BindUtils.postGlobalCommand(null, null, "reload", null);
			window.detach();
		} catch (PayException ex) {
			Messagebox.show(StringUtils.localize(ex.getReason()), StringUtils.localize("Error"), Messagebox.OK,
					Messagebox.ERROR);
		} catch (AccessDeniedException ex) {
			Messagebox.show(StringUtils.localize("ErrorRights"), StringUtils.localize("Error"), Messagebox.OK, Messagebox.ERROR);
		}
	}

	public Date getPayDate() {
		return payDate;
	}

	public void setPayDate(Date payDate) {
		this.payDate = payDate;
	}
}
