package com.example.demo.module.login;

import com.example.demo.common.GlobalConfig;
import com.example.demo.common.MD5Tool;
import com.example.demo.table.UserLogin;

public class LoginToken {
    public int uid;
    public int serverIndex;
    public long expireTime;
    public String md5Sign;
    public String businessServerURL;

    public static LoginToken parseClientToken(String clientToken) {
        String[] params = clientToken.split("&");
        if (params.length < 3) return null;
        String rawToken = params[1];
        String[] rawTokenSP = rawToken.split("卍");
        if (rawTokenSP.length < 4) return null;
        LoginToken loginToken = new LoginToken();
        try {
            loginToken.uid = Integer.valueOf(rawTokenSP[0]);
            loginToken.serverIndex = Integer.valueOf(rawTokenSP[1]);
            loginToken.expireTime = Long.valueOf(rawTokenSP[2]);
            loginToken.md5Sign = rawTokenSP[3];
            loginToken.businessServerURL = params[2];
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return loginToken;
    }

    public static LoginToken parseUserLogin(UserLogin userLogin, int appServerIndex) {
        LoginToken loginToken = new LoginToken();
        loginToken.uid = userLogin.getId();
        loginToken.serverIndex = appServerIndex;
        loginToken.expireTime = userLogin.getToken_timeout();
        loginToken.md5Sign = loginToken.makeMD5Sign();
        loginToken.businessServerURL = GlobalConfig.getBusinessWS(appServerIndex);
        return loginToken;
    }

    public String toClientToken() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(uid);
        stringBuilder.append("&");
        stringBuilder.append(uid);
        stringBuilder.append("卍");
        stringBuilder.append(serverIndex);
        stringBuilder.append("卍");
        stringBuilder.append(expireTime);
        stringBuilder.append("卍");
        stringBuilder.append(md5Sign);
        stringBuilder.append("&");
        stringBuilder.append(businessServerURL);
        return stringBuilder.toString();
    }

    private String makeMD5Sign() {
        return MD5Tool.makeMD5(uid + "@" + serverIndex + "@" + expireTime + "@SB-2022");
    }

    public boolean isMD5SignRight() {
        return makeMD5Sign().equals(md5Sign);
    }

    public boolean isTimeValid() {
        return System.currentTimeMillis() < expireTime;
    }

    public String getLoginTokenForDatabase() {
        return md5Sign;
    }
}
