package info.bukova.isspst.services.settings;

import info.bukova.isspst.StringUtils;
import info.bukova.isspst.data.NumberSeries;
import info.bukova.isspst.data.Season;
import info.bukova.isspst.services.AbstractOwnedService;
import info.bukova.isspst.services.numberseries.NumberSeriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Pepa Rokos
 */
public class SeasonServiceImpl extends AbstractOwnedService<Season> implements SeasonService {
	private Season activeSeason;
	@Autowired
	private NumberSeriesService numberSeriesService;

	@Transactional
	@Override
	public Season addSeason() {
		Season season = new Season();
		season.setDescription(StringUtils.localize("SeasonsNewSeason"));
		season.setValidFrom(new Date());
		season.setActive(true);

		Season last = selectSingle("from Season where validTo Is Null");
		add(season);

		last.setValidTo(new Date());
		last.setActive(false);
		update(last);


		activeSeason = null;

		List<NumberSeries> numSeries = numberSeriesService.getSeriesForSeason(last);
		for (NumberSeries ns: numSeries) {
			String txt = ns.getPrefix().replaceAll("[0-9]+", "");
			String numTxt = ns.getPrefix().replaceAll("[a-zA-Z]+", "");

			int num = 0;
			try {
				num = Integer.valueOf(numTxt);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String newPrefix = txt + String.valueOf(num + 1);

			NumberSeries newNumSer = new NumberSeries();
			newNumSer.setPrefix(newPrefix);
			newNumSer.setModule(ns.getModule());
			newNumSer.setNumber(1);
			newNumSer.setSeason(season);
			numberSeriesService.add(newNumSer);
		}
		return season;
	}

	@Transactional
	@Override
	public Season getActive() {
		if (activeSeason == null) {
			activeSeason = selectSingle("from Season where active = true");
		}

		if (activeSeason == null) {
			throw new SeasonException("Active_season_not_set");
		}
		return activeSeason;
	}

	@Override
	@Transactional
	public List<Season> getAllSeasons() {
		return getAll();
	}

	@Transactional
	@Override
	public void setActive(Season season) {
		for (Season s: getAll()) {
			s.setActive(false);
			update(s);
		}

		Season s = dao.getById(season.getId());

		if (s == null) {
			throw new SeasonException("Season_not_in_database");
		}

		s.setActive(true);
		activeSeason = s;
	}
}
