package org.ros.chatto.controller;

import java.security.Principal;
import java.time.Instant;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.ros.chatto.dto.AdminUserDTO;
import org.ros.chatto.dto.ChatMessageDTO;
import org.ros.chatto.dto.ReencryptionDTO;
import org.ros.chatto.service.AdminService;
import org.ros.chatto.service.ChatService;
import org.ros.chatto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminRESTController {
	private final ChatService chatService;

	private final UserService userService;

	private final AdminService adminService;

	@PostMapping(value = "/post/re-encrypt", consumes = { "application/json" })
	public ResponseEntity<ReencryptionDTO> reencryptMessages(
			@RequestBody @Valid List<ReencryptionDTO> reencryptionDTOs,
			Principal principal) {
		if (reencryptionDTOs.size() > 0) {
			chatService.reencryptMessages(reencryptionDTOs);
		}
		return new ResponseEntity<ReencryptionDTO>(HttpStatus.OK);
	}

	@GetMapping(value = "/get/messages/{userName}")
	public List<ReencryptionDTO> sendAllMessages(@PathVariable String userName,
			Principal principal) {
		List<ReencryptionDTO> reencryptionDTOs = chatService
				.getAllMessagesForReencryption(principal.getName(), userName);
		return reencryptionDTOs;
	}

	@GetMapping(value = "/get/messages/{userName}/{lastMessageTime}")
	public List<ChatMessageDTO> sendNewMessages(@PathVariable String userName,
			@PathVariable Instant lastMessageTime, Principal principal) {
		List<ChatMessageDTO> chatMessageDTOs = chatService
				.getNewMessages(principal.getName(), userName, lastMessageTime);
		return chatMessageDTOs;
	}

	@GetMapping("/regular-users")
	public List<String> getAllRegularUsers() {
		return userService.getAllRegularUsers();
	}

	@GetMapping("/get/users")
	public List<AdminUserDTO> getAllOtherUsers(Principal principal) {
		return adminService.getOtherUsers(principal.getName());
	}
}
