package com.jty.wsxt.infrastructure.security;

import com.jty.wsxt.infrastructure.support.Result;
import com.jty.wsxt.infrastructure.support.ResultCode;
import com.jty.wsxt.interfaces.dto.NrscTeacherDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 安全权限Controller
 *
 * @author Jason
 * @since 2018/12/14 09:53
 */
@RestController
public class SecurityController {

    @Autowired
    private SecurityProperties properties;


    /**
     * 当需要身份认证时跳转到这个controller
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code= HttpStatus.UNAUTHORIZED)
    public Result requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
    }

    @GetMapping("/user")
    public Authentication getAuthentication(Authentication authentication){
        return authentication;
    }

    @RequestMapping("/me")
    public Result getUserDetails(@AuthenticationPrincipal MyUserDetail userDetails){
        NrscTeacherDto nrscTeacherDto = new NrscTeacherDto();
        nrscTeacherDto.setAccount(userDetails.getUsername());
        nrscTeacherDto.setUsername(userDetails.getRealName());
        nrscTeacherDto.setPassword(userDetails.getPassword());
        nrscTeacherDto.setId(userDetails.getUserId());
        nrscTeacherDto.setAuthorities(userDetails.getAuthorities());
        return  Result.success(nrscTeacherDto);
    }

    @GetMapping("/user/id")
    public Integer getUserId(@AuthenticationPrincipal MyUserDetail userDetails){
        return userDetails.getUserId();
    }

    @GetMapping("/user/name")
    public String getUserName(@AuthenticationPrincipal MyUserDetail userDetails){
        return userDetails.getUsername();
    }
}