package info.bukova.isspst.ui.settings;

import info.bukova.isspst.Module;
import info.bukova.isspst.ModuleUtils;
import info.bukova.isspst.StringUtils;
import info.bukova.isspst.data.NumberSeries;
import info.bukova.isspst.data.Season;
import info.bukova.isspst.services.numberseries.NumberSeriesService;
import info.bukova.isspst.services.settings.SeasonService;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

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

/**
 * @author Pepa Rokos
 */
public class SeasonsVM {
	@WireVariable
	private SeasonService seasonService;
	@WireVariable
	private NumberSeriesService numericSeriesService;
	private List<Season> seasons;
	private List<NumberSeries> numSeries;
	private Map<String, Module> moduleMap;

	@Init
	public void init() {
		seasons = seasonService.getAll();
		numSeries = numericSeriesService.getSeriesForSeason(seasonService.getActive());
		moduleMap = new HashMap<String, Module>();
		for (Module m : ModuleUtils.getActiveModules()) {
			moduleMap.put(m.getId(), m);
		}
	}

	public Map<String, Module> getModuleMap() {
		return moduleMap;
	}

	@Command
	//@NotifyChange({"seasons", "numSeries"})
	public void addSeason() {
		Messagebox.show(StringUtils.localize("SeasonsNewSeasonDialog"), StringUtils.localize("SeasonsNewSeason"), Messagebox.YES | Messagebox.NO, Messagebox.QUESTION,
				new EventListener<Event>() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer)event.getData()).intValue() == Messagebox.YES) {
							Season newSeason = seasonService.addSeason();
							seasons = seasonService.getAll();
							numSeries = numericSeriesService.getSeriesForSeason(seasonService.getActive());
							BindUtils.postNotifyChange(null, null, SeasonsVM.this, "seasons");
							BindUtils.postNotifyChange(null, null, SeasonsVM.this, "numSeries");
						}
					}
				});
	}

	@Command
	public void save(@BindingParam("window") Window win) {
		for(Season s: seasons) {
			seasonService.update(s);
		}

		for(NumberSeries n: numSeries) {
			numericSeriesService.update(n);
		}

		win.detach();
	}

	@Command
	@NotifyChange({"numSeries", "seasons"})
	public void activate(@BindingParam("season") Season season) {
		seasonService.setActive(season);
		seasons = seasonService.getAll();
		numSeries = numericSeriesService.getSeriesForSeason(season);
	}

	public List<Season> getSeasons() {
		return seasons;
	}

	public List<NumberSeries> getNumSeries() {
		return numSeries;
	}

	public boolean isCanSave() {
		return true;
	}
}
