package com.yida.data.auth.controller;

import com.yida.data.auth.manager.UserManager;
import com.yida.data.auth.service.SecurityService;
import com.yida.data.auth.service.ValidateCodeService;
import com.yida.data.common.core.entity.FebsResponse;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.exception.ValidateCodeException;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author MrBird
 */
@Controller
@RequiredArgsConstructor
public class SecurityController {

    private final ValidateCodeService validateCodeService;
    private final SecurityService securityService;
    private final UserManager userManager;
    private final ConsumerTokenServices consumerTokenServices;

    @ResponseBody
    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }

    @ResponseBody
    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
        validateCodeService.create(request, response);
    }

    @RequestMapping("login")
    public String login() {
        return "login";
    }

    @RequestMapping("test")
    public String test() {
        return "test";
    }

    @ResponseBody
    @DeleteMapping("signout")
    public FebsResponse signout(HttpServletRequest request, @RequestHeader("Authorization") String token) {
        token = StringUtils.replace(token, "bearer ", StringConstant.EMPTY);
        consumerTokenServices.revokeToken(token);
        return new FebsResponse().message("signout");
    }

    @ApiOperation("获取学校负责人登录信息")
    @ResponseBody
    @GetMapping("/inSchool")
    public FebsResponse inSchool(Long schoolId) {
        return new FebsResponse().data(securityService.getSchoolToken(schoolId));
    }
}
