package de.champonthis.buntspecht.businesslogic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import de.champonthis.buntspecht.model.SystemProperty;
import de.champonthis.buntspecht.repository.SystemPropertyRepository;

@Component
public class SystemPropertyManager {

	@Autowired
	private SystemPropertyRepository systemPropertyRepository;

	public boolean has(String key) {
		return systemPropertyRepository.existsById(key);
	}

	public String get(String key) {
		return systemPropertyRepository.findById(key).orElse(new SystemProperty()).getValue();
	}

	public String get(String key, String defaultValue) {
		return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue();
	}

	public boolean getBoolean(String key) {
		return getBoolean(key, false);
	}

	public boolean getBoolean(String key, boolean defaultValue) {
		return Boolean.valueOf(get(key, String.valueOf(defaultValue)));
	}

	public int getInteger(String key) {
		return getInteger(key, 0);
	}

	public int getInteger(String key, int defaultValue) {
		return Integer.valueOf(get(key, String.valueOf(defaultValue)));
	}

	public long getLong(String key) {
		return getLong(key, 0L);
	}

	public long getLong(String key, long defaultValue) {
		return Long.valueOf(get(key, String.valueOf(defaultValue)));
	}

	public void add(String key, String value) {
		Assert.isTrue(!systemPropertyRepository.existsById(key),
				"System Property already exists, use update method to change value!");
		systemPropertyRepository.save(new SystemProperty(key, value));
	}

	public void update(String key, String value) {
		Assert.isTrue(systemPropertyRepository.existsById(key),
				"System Property does not exists, use add method to add new!");
		SystemProperty systemProperty = systemPropertyRepository.findById(key).get();
		systemProperty.setValue(value);
		systemPropertyRepository.save(systemProperty);
	}

	public void set(String key, String value) {
		if (systemPropertyRepository.existsById(key)) {
			update(key, value);
		} else {
			add(key, value);
		}
	}

}
