package io.smart7.commerce.web;



import java.io.UnsupportedEncodingException;
import java.util.Collection;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import io.smart7.commerce.model.CurrentUser;
import io.smart7.commerce.model.Message;
import io.smart7.commerce.model.MessageSubject;
import io.smart7.commerce.service.MessageService;

@Controller
@Navigation(Section.MESSAGE)
public class MessageController {

	private static final Logger LOGGER = LoggerFactory.getLogger(MessageController.class);
	
    private final MessageService messageService;

    @Autowired
    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }


    @ModelAttribute("subjects")
    public Collection<MessageSubject> populateMessageSubjects() {
    	return this.messageService.findMessageSubjects();
    }
    
    
    
    @GetMapping("/message")
    public String messageForm(Model model) {
        LOGGER.debug("GET message is called.");
        model.addAttribute("messageForm",new Message());
        return "message";
    }


    @RequestMapping(path = "/message", method = RequestMethod.POST)
    public String message(@Valid Message message, BindingResult bindingResult,
                          @AuthenticationPrincipal CurrentUser user, RedirectAttributes attributes, Model model) {
        LOGGER.debug("POST message is called.");
        if (bindingResult.hasErrors()) {
            model.addAttribute("message", message);
            return "message";
        } else {
            this.messageService.createMessage(message);
            try {
                messageService.sendPlainTextEmail(message);
                attributes.addFlashAttribute("successMessage", "Thanks! Your message has been submitted.");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return "redirect:/message";
        }
    }	
}
