package eu.eudat.controllers;

import eu.eudat.logic.managers.ContactEmailManager;
import eu.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;

@RestController
@CrossOrigin
@RequestMapping(value = "api/contactEmail")
public class ContactEmail {
	private static final Logger logger = LoggerFactory.getLogger(ContactEmail.class);

	private ContactEmailManager contactEmailManager;

	public ContactEmail(ContactEmailManager contactEmailManager) {
		this.contactEmailManager = contactEmailManager;
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
	public @ResponseBody
	ResponseEntity sendContactEmail(@RequestBody ContactEmailModel contactEmailModel, Principal principal) {
		try {
			this.contactEmailManager.emailValidation(contactEmailModel);
			this.contactEmailManager.sendContactEmail(contactEmailModel, principal);
			return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage()));
		}
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST, path = "public", consumes = "application/x-www-form-urlencoded", produces = "application/json")
	public @ResponseBody
	ResponseEntity sendContactEmailNoAuth(@ModelAttribute PublicContactEmailModel contactEmailModel) {
		try {
			this.contactEmailManager.sendContactEmailNoAuth(contactEmailModel);
			return ResponseEntity.status(HttpStatus.NO_CONTENT).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message(ex.getMessage()));
		}
	}
}
