package premium_store.controller.controller;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import premium_store.controller.DTO.UserSignupDto;
import premium_store.model.GameClient;
import premium_store.model.UserRole;
import premium_store.service.GameClientService;

import javax.validation.Valid;
import javax.validation.ValidationException;

@Controller
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
public class UserSignupMvcController {
    public static final String SIGNUP_URL = "/signup";

    private final GameClientService clientService;

    public UserSignupMvcController(GameClientService clientService) {
        this.clientService = clientService;
    }

    @GetMapping
    public String showSignupForm(Model model) {
        model.addAttribute("clientDTO", new UserSignupDto());

        return "signup";
    }

    @PostMapping
    public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
                         BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("errors", bindingResult.getAllErrors());
            return "signup";
        }
        try {
            final GameClient client = clientService.addClient(userSignupDto.getLogin(), userSignupDto.getEmail(), userSignupDto.getPassword(), userSignupDto.getBalance(), userSignupDto.getPasswordConfirm(), UserRole.USER);
            return "redirect:/login?created=" + client.getLogin();
        } catch (ValidationException e) {
            model.addAttribute("errors", e.getMessage());
            return "signup";
        }
    }

}
