package es.uv.garcosda.output.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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 org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import es.uv.garcosda.shared.domain.Mail;
import es.uv.garcosda.shared.domain.User;

@RestController
@RequestMapping("/api/v1")
public class OutputController {

	@Autowired
    private RestTemplate template;
	
	@Value("${mailer.data.url}")
	private String api;
	
	@GetMapping("status")
	public ResponseEntity<String> test(){
		return new ResponseEntity<String>("Running", HttpStatus.OK);
	}
	
	@PostMapping
	@HystrixCommand(fallbackMethod="fallbackDataApi")
	public ResponseEntity<?> sendMail(@RequestBody Mail mail){
		
		User from = this.getUser(mail.getFrom());
		User to = this.getUser(mail.getTo());
		if(from.getId() == null || to.getId() == null) {
			return new ResponseEntity<Mail>(new Mail(), HttpStatus.NOT_FOUND);
		}
		
		mail.setFrom(from.getId());
		mail.setTo(to.getId());
		ResponseEntity<Mail> response;
		try {
			response = template.postForEntity(api+"/mails", mail, Mail.class); 
		}
		catch(ResourceAccessException e){
			return new ResponseEntity<Mail>(new Mail(), HttpStatus.SERVICE_UNAVAILABLE);
		}
		if(response.getStatusCode() == HttpStatus.OK) {
			return new ResponseEntity<Mail>(response.getBody(), HttpStatus.OK);
		}
		return new ResponseEntity<Mail>(new Mail(), HttpStatus.BAD_REQUEST);
	}
	
	private User getUser(String mail) {
		ResponseEntity<User> response;
		try {
			response = template.getForEntity(api+"/users/email/"+mail, User.class); 
		}
		catch(ResourceAccessException e){
			return new User();
		}
		if(response.getStatusCode() == HttpStatus.OK) {
			return response.getBody();
		}
		return new User();
	}
	
	@SuppressWarnings("unused")
	private ResponseEntity<?> fallbackDataApi() {
		return new ResponseEntity<String>("Not available at this moment, try again later.", HttpStatus.SERVICE_UNAVAILABLE);
	}
}
