package es.uv.garcosda.mail.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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.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.RestController;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

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

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

	@Autowired
    private RestTemplate template;
	
	@Value("${mailer.output.url}")
	private String output_api;
	@Value("${mailer.input.url}")
	private String input_api;
	@Value("${mailer.data.url}")
	private String data_api;
	
	@GetMapping("status")
	public ResponseEntity<String> test(){
		return new ResponseEntity<String>("Running", HttpStatus.OK);
	}
	
	@GetMapping("{mail}")
	public ResponseEntity<?> getMails(@PathVariable String mail){
		ResponseEntity<MailDTO[]> response;
		List<MailDTO> mails = new ArrayList<MailDTO>();
		try {
			response = template.getForEntity(input_api+"/"+mail, MailDTO[].class); 
		}
		catch(ResourceAccessException e){
			return new ResponseEntity<List<MailDTO>>(mails, HttpStatus.SERVICE_UNAVAILABLE);
		}
		if(response.getStatusCode() == HttpStatus.OK) {
			mails = Arrays.stream(response.getBody()).collect(Collectors.toList());
			return new ResponseEntity<List<MailDTO>>(mails, HttpStatus.OK);
		}
		return new ResponseEntity<List<MailDTO>>(mails, HttpStatus.SERVICE_UNAVAILABLE);
	}
	
	@DeleteMapping("{id}")
	public ResponseEntity<?> deleteMail(@PathVariable String id){
		try {
			template.delete(input_api+"/"+id);
			return new ResponseEntity<String>(id, HttpStatus.OK);
		}
		catch(ResourceAccessException e){
			return new ResponseEntity<String>("Not available", HttpStatus.SERVICE_UNAVAILABLE);
		}
	}
	
	@PostMapping
	public ResponseEntity<?> sendMail(@RequestBody Mail mail){		
		ResponseEntity<Mail> response;
		try {
			response = template.postForEntity(output_api, 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.SERVICE_UNAVAILABLE);
	}
		
}
