package de.champonthis.buntspecht.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import de.champonthis.buntspecht.controller.BaseController;
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
import de.champonthis.buntspecht.model.SystemProperty;
import de.champonthis.buntspecht.repository.SystemPropertyRepository;

@RestController
@RequestMapping("/system/properties")
public class SystemPropertiesController extends BaseController {

	@Autowired
	private SystemPropertyRepository systemPropertyRepository;

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@GetMapping()
	public List<SystemProperty> getProperties(@RequestParam("page") Optional<Integer> pageParameter,
			@RequestParam("size") Optional<Integer> sizeParameter) {
		Sort sort = Sort.by("key").ascending();
		return systemPropertyRepository.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
				.getContent();
	}

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@GetMapping("/{key}")
	public SystemProperty getProperty(@PathVariable("key") String key) {
		if (!systemPropertyRepository.existsById(key)) {
			throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
		}

		return systemPropertyRepository.findById(key).get();
	}

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@PostMapping("")
	public SystemProperty createOrUpdate(@RequestBody SystemProperty systemProperty) {
		return systemPropertyRepository.save(systemProperty);
	}

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@PostMapping("/list")
	public List<SystemProperty> createOrUpdateList(@RequestBody List<SystemProperty> systemProperties) {
		List<SystemProperty> result = new ArrayList<>();
		for (SystemProperty systemProperty : systemProperties) {
			result.add(
					systemPropertyRepository.save(systemProperty));
		}
		return result;
	}

	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@DeleteMapping("/{key}")
	public void deleteProperty(@PathVariable("key") String key) {
		if (!systemPropertyRepository.existsById(key)) {
			throw new EntityResponseStatusException(HttpStatus.NOT_MODIFIED);
		}

		systemPropertyRepository.deleteById(key);
	}
}
