package eu.eudat.controllers;

import eu.eudat.logic.managers.LockManager;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.lock.Lock;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping(value = {"/api/lock/"})
public class LockController {

	private LockManager lockManager;

	@Autowired
	public LockController(LockManager lockManager) {
		this.lockManager = lockManager;
	}

	@Transactional
	@RequestMapping(method = RequestMethod.GET, path = "target/status/{id}")
	public @ResponseBody ResponseEntity<ResponseItem<Boolean>> getLocked(@PathVariable String id, Principal principal) throws Exception {
		boolean locked = this.lockManager.isLocked(id, principal);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Boolean>().status(ApiMessageCode.SUCCESS_MESSAGE).message("locked").payload(locked));
	}

	@Transactional
	@RequestMapping(method = RequestMethod.DELETE, path = "target/unlock/{id}")
	public @ResponseBody ResponseEntity<ResponseItem<String>> unlock(@PathVariable String id, Principal principal) throws Exception {
		this.lockManager.unlock(id, principal);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload("Lock Removed"));
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
	public @ResponseBody ResponseEntity<ResponseItem<UUID>> createOrUpdate(@RequestBody Lock lock, Principal principal) throws Exception {
		eu.eudat.data.entities.Lock result = this.lockManager.createOrUpdate(lock, principal);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(result.getId()));
	}

	@RequestMapping(method = RequestMethod.GET, path = "target/{id}")
	public @ResponseBody ResponseEntity<ResponseItem<Lock>> getSingle(@PathVariable String id, Principal principal) throws Exception {
		Lock lock = this.lockManager.getFromTarget(id, principal);
		return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Lock>().status(ApiMessageCode.NO_MESSAGE).payload(lock));
	}
}
