package cn.reghao.devops.mgr.admin.controller;

import cn.reghao.devops.mgr.admin.model.dto.RsaPubkey;
import cn.reghao.devops.mgr.admin.service.CodeService;
import cn.reghao.devops.mgr.admin.service.PubkeyService;
import cn.reghao.jutil.jdk.result.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author reghao
 * @date 2022-02-18 16:05:30
 */
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/api/account/code")
public class AccountCodeController {
    private final CodeService codeService;
    private final PubkeyService pubkeyService;

    public AccountCodeController(CodeService codeService, PubkeyService pubkeyService) {
        this.codeService = codeService;
        this.pubkeyService = pubkeyService;
    }

    @ApiOperation(value = "获取公钥", notes = "N")
    @GetMapping(value = "/pubkey", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getPubkey() throws NoSuchAlgorithmException {
        RsaPubkey rsaPubkey = pubkeyService.getPubkey();
        return WebResult.success(rsaPubkey);
    }

    @ApiOperation(value = "获取图形验证码", notes = "N")
    @GetMapping(value = "/captcha", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getCaptcha() throws IOException {
        InputStream in = codeService.generateCaptcha();
        byte[] base64Bytes = Base64.getEncoder().encode(in.readAllBytes());
        String base64Str = new String(base64Bytes, StandardCharsets.UTF_8);
        String imageStr = String.format("data:image/jpeg;base64,%s", base64Str);
        return WebResult.success(imageStr);
    }
}
