/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.geekidea.springbootplus.framework.shiro.jwt;

import com.auth0.jwt.interfaces.DecodedJWT;
import io.geekidea.springbootplus.framework.shiro.util.JwtUtil;
import io.geekidea.springbootplus.framework.util.IpUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.shiro.authc.HostAuthenticationToken;

import java.util.Date;

/**
 * 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;

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

    /**
     * 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, String clientId, 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.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;
    }

}
