package com.wecloud.im.security.jwt;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Date;

import org.apache.shiro.authc.HostAuthenticationToken;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wecloud.im.core.util.IpUtil;
import com.wecloud.im.security.util.JwtUtil;

/**
 * Shiro JwtToken对象
 *
 * @author geekidea
 * @date 2019-09-27
 * @since 1.3.0.RELEASE
 **/
@Data
@Accessors(chain = true)
public class JwtToken implements HostAuthenticationToken {
    private static final long serialVersionUID = 5101247566043093405L;

    /**
     * 登录ip
     */
    private String host;

    /**
     * client id
     */
    private Long fkClientId;

    /**
     * 登录clientId
     */
    private String clientId;

    /**
     * appId
     */
    private Long appId;

    /**
     * app
     */
    private String appKey;

    /**
     * 登录盐值
     */
    private String salt;
    /**
     * 登录token
     */
    private String token;
    /**
     * 创建时间
     */
    private Date createDate;
    /**
     * 多长时间过期
     */
    private long expireSecond;
    /**
     * 过期日期
     */
    private Date expireDate;

    private String principal;

    private String credentials;

    /**
     * 1 web, 2 安卓, 3 ios, 4 pc-win, 5 pc-macOs
     */
    private Integer platform;

    public static JwtToken build(String token, String salt, long expireSecond, Long fkClientId,
                                 String clientId, Long appId, String appKey, Integer platform) {
        DecodedJWT decodedJwt = JwtUtil.getJwtInfo(token);
        Date createDate = decodedJwt.getIssuedAt();
        Date expireDate = decodedJwt.getExpiresAt();
        JwtToken jwtToken = new JwtToken();
        jwtToken.setClientId(clientId);
        jwtToken.setFkClientId(fkClientId);
        jwtToken.setAppId(appId);
        jwtToken.setAppKey(appKey);
        jwtToken.setToken(token);
        jwtToken.setHost(IpUtil.getRequestIp());
        jwtToken.setSalt(salt);
        jwtToken.setCreateDate(createDate);
        jwtToken.setExpireSecond(expireSecond);
        jwtToken.setExpireDate(expireDate);
        jwtToken.setPlatform(platform);
        return jwtToken;
    }

    @Override
    public Object getPrincipal() {
        return token;
    }

    @Override
    public Object getCredentials() {
        return token;
    }

}
