package cn.datax.auth.aspect;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.io.IOException;
import java.util.Map;

public class DataOauthResponseSerializer extends StdSerializer<DataOauthResponse> {

    public DataOauthResponseSerializer() {
        super(DataOauthResponse.class);
    }

    @Override
    public void serialize(DataOauthResponse value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) value.getData();
        gen.writeStartObject();
        gen.writeNumberField("code", value.getCode());
        if(StrUtil.isNotBlank(value.getMsg())){
            gen.writeStringField("msg", value.getMsg());
        }
        gen.writeBooleanField("success", value.isSuccess());
        gen.writeNumberField("timestamp", System.currentTimeMillis());
        if(null != oAuth2AccessToken){
            Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation();
            map.put("access_token", oAuth2AccessToken.getValue());
            map.put("token_type", oAuth2AccessToken.getTokenType());
            map.put("refresh_token", oAuth2AccessToken.getRefreshToken().getValue());
            map.put("expires_in", oAuth2AccessToken.getExpiresIn());
            map.put("scope", oAuth2AccessToken.getScope());
            gen.writeObjectField("data", map);
        }
        gen.writeEndObject();
    }
}
