package cn.reghao.oss.console.account.controller;

import cn.reghao.oss.console.account.model.dto.RsaPubkey;
import cn.reghao.oss.console.account.service.CodeService;
import cn.reghao.oss.console.account.service.PubkeyService;
import cn.reghao.jutil.jdk.result.WebResult;
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
 */
@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;
    }

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

    @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);
    }
}
