package com.eactive.httpmockserver.user.controller;

import com.eactive.httpmockserver.common.util.SecurityUtil;
import com.eactive.httpmockserver.user.dto.PasswordChangeRequestDTO;
import com.eactive.httpmockserver.user.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class AccountController {

    public static final String UPDATE_PW = "page/updatePw";
    private Validator validator;

    private UserService userService;

    public AccountController(Validator validator, UserService userService) {
        this.validator = validator;
        this.userService = userService;
    }

    @GetMapping("/change_password.do")
    public String changePassword(@ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO) {
        return UPDATE_PW;
    }

    @PostMapping(value = "/update_password.do")
    @Transactional
    public String updatePassword(ModelMap model, @ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO,
                                 BindingResult result) {

        validator.validate(passwordChangeRequestDTO, result);

        if (result.hasErrors()) {
            model.addAttribute("errors", result);
        } else {
            String oldPassword = passwordChangeRequestDTO.getOldPassword();
            String newPassword = passwordChangeRequestDTO.getNewPassword();
            String newPassword2 = passwordChangeRequestDTO.getNewPassword2();
            String resultMsg = userService.updateUserPassword(SecurityUtil.getCurrentUserEsntlId(), oldPassword, newPassword, newPassword2);

            model.addAttribute("resultMsg", resultMsg);
            model.addAttribute("passwordChangeRequest", new PasswordChangeRequestDTO());
        }


        return UPDATE_PW;
    }


}
