package com.qmth.themis.common.token;

import com.qmth.themis.common.contanst.Constants;
import com.qmth.themis.common.enums.Platform;
import com.qmth.themis.common.util.RSAUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * 两步登录验证令牌工具
 * 
 * @author luoshi
 *
 */
public class VerifyToken implements Constants {

    private static final String JOINER = "&";

    private String mobileNumber;

    private Platform platform;

    private String deviceId;

    private long timestamp;

    public static String encode(String mobileNumber, Platform platform, String deviceId, RSAPrivateKey privateKey) {
        if (mobileNumber == null || platform == null || deviceId == null || privateKey == null) {
            throw new IllegalArgumentException("verify token param invalid");
        }
        try {
            return RSAUtils.encrypt(StringUtils.joinWith(JOINER, mobileNumber, platform.toString(), deviceId,
                    String.valueOf(System.currentTimeMillis())), privateKey);
        } catch (Exception e) {
            return "";
        }
    }

    public static VerifyToken decode(String token, RSAPublicKey publicKey) {
        VerifyToken vt = new VerifyToken();
        try {
            String[] array = StringUtils.split(RSAUtils.decrypt(token, publicKey), JOINER);
            vt.mobileNumber = array[0];
            vt.platform = Platform.findByName(array[1]);
            vt.deviceId = array[2];
            vt.timestamp = Long.valueOf(array[3]);
        } catch (Exception e) {
        }
        return vt;
    }

    public boolean validate(Platform platform, String deviceId) {
        long current = System.currentTimeMillis();
        return this.mobileNumber != null && this.platform != null && this.platform == platform && this.deviceId != null
                && this.deviceId.equals(deviceId) && this.timestamp > 0 && this.timestamp < current
                && (current - this.timestamp) < VERIFY_TOKEN_EXPIRE_SECONDS * 1000;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public Platform getPlatform() {
        return platform;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public long getTimestamp() {
        return timestamp;
    }

}
