package de.oaa.xxx.games.chastity.timelock;

import static de.oaa.xxx.util.ValidationResult.ERROR;
import static de.oaa.xxx.util.ValidationResult.OK;
import static de.oaa.xxx.util.ValidationResult.WARNING;

import java.util.List;
import java.util.UUID;

import de.oaa.xxx.games.chastity.spinningwheel.EntryType;
import de.oaa.xxx.games.chastity.tasks.TaskMode;
import de.oaa.xxx.util.ValidationResult;

public class TimeLockTemplateService {

	private TimeLockTemplateRepository timelockTemplateRepository;

	public TimeLockTemplateService(TimeLockTemplateRepository timelockTemplateRepository) {
		this.timelockTemplateRepository = timelockTemplateRepository;
	}
	
	public List<TimeLockTemplate> all(UUID ownderId) {
		return timelockTemplateRepository.findByOwner(ownderId).stream().map(template -> template.toTimeLockTemplate()).toList();
	}
	
	public boolean safe(TimeLockTemplate template) {
		var result = validate(template);
		if (ValidationResult.OK == result || ValidationResult.WARNING == result) {	
			timelockTemplateRepository.save(TimeLockTemplateEntity.fromTemplate(template));
			return true;
		}
		return false;
	}
	
	public ValidationResult validate(TimeLockTemplate template) {
		if (template == null) {
			return ERROR;
		}
		if (template.owner() == null ||
				template.name() == null ||	
				template.maxTimeInMinutes() == null) {
			return ERROR;
		}
		if (template.taskEveryMinutes() != null) {
			if (template.tasks() == null || template.tasks().isEmpty()) {
				return ERROR;
			}
			if (template.spinningWheelEntries() != null && !template.spinningWheelEntries().isEmpty()
					&& template.spinningWheelEntries().stream().anyMatch(entry -> EntryType.TASK == entry.getType())) {
				return ERROR;
			}
			if (template.minTasksPerDay() != null) {
				int minTime = getMinimumTime(template);
				if (minTime > (24*60)) {
					return ERROR;
				} else if (minTime > (12*60)) {
					return WARNING;
				} 
			}
		} else if (template.minTasksPerDay() != null) {
			return ERROR;
		}
		if (template.spinsEveryMinutes() != null) {
			if (template.spinningWheelEntries() == null || template.spinningWheelEntries().isEmpty()) {
				return ERROR;
			}
			if (template.minSpinsPerDay() != null) {
				int minTime = template.spinsEveryMinutes() * template.minSpinsPerDay();
				if (minTime > (24*60)) {
					return ERROR;
				} else if (minTime > (12*60)) {
					return WARNING;
				} 
			}
		} else if (template.minSpinsPerDay() != null) {
			return ERROR;
		}
		if (template.hygineOpeningEveryMinites() != null && template.hygineOpeningDurationMinutes() == null) {
			return ERROR;
		}
		return OK;
	}

	private Integer getMinimumTime(TimeLockTemplate template) {
		int votetime = 0;
		if (TaskMode.COMMUNITY == template.taskMode() || TaskMode.KEYHOLDER == template.taskMode()) {
			votetime = 60 * template.minTasksPerDay();
		}
		int waittime = template.taskEveryMinutes() * template.minTasksPerDay();
		return votetime + waittime;
	} 
}
