package com.tcl.ah.module.token;

import com.tcl.ah.module.token.data.DataWraper;
import com.tcl.ah.module.token.data.Key;
import com.tcl.ah.module.token.data.Token;
import com.tcl.ah.security.KeyHelper;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TokenHelper {
    private static Token mToken = new Token();

    public static Token getToken() {
        return mToken;
    }

    private static DataWraper<Token> getTokenFromNet(String url, String mac, Token token) {
        OkHttpClient client = new OkHttpClient();
        url = url + Token.TOKEN+"?mac=" + mac;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                DataWraper<Token> container = Token.parseJson(result);
                token.details="token json:"+result;
                return container;
            } else {
                token.details = response.toString();
            }
        } catch (Exception e) {
            token.details = e.toString();
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isExpired() {
        if (mToken != null && Math.abs(System.currentTimeMillis() / 1000 - mToken.currentTime) < (mToken.timeout - 10)) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean updateToken(String url, String mac) {
        if (mToken != null && !isExpired()) {
            System.out.println("token:token is fresh.");
            return true;
        }else{
            System.out.println("token:token is exired.");
        }
        DataWraper<Token> container = getTokenFromNet(url, mac, mToken);
        boolean isDecrypt = false;
        isDecrypt = container == null ? false : parseAppCode(mac, container.data);
        int count = 3;
        while ((container == null || container.code != 0 || !isDecrypt) && count >= 0) {
            container = getTokenFromNet(url, mac, mToken);
            isDecrypt = container == null ? false : parseAppCode(mac, container.data);
            count--;
        }
        if (container != null && container.code == 0 && container.data != null && isDecrypt) {
            mToken.timeout = container.data.timeout;
            mToken.token = container.data.token;
            mToken.timestamp = container.data.timestamp;
            mToken.currentTime = System.currentTimeMillis() / 1000;
            mToken.setDecryptAppCode(container.data.getDecryptAppCode());
            return true;
        } else {
            if (container != null) {
                mToken.details = "token response code is error:"+mToken.details;
            }
            return false;
        }
    }

    /**
     * @param mac mac 地址必须全部大写，并且不带冒号,2020/03/31 与服务端约定
     * @return
     */
    private static boolean parseAppCode(String mac, Token token) {
        if (mac == null || mac.trim().length() == 0) {
            return false;
        }
        if (token == null) {
            return false;
        }
        if (token.appCode != null && token.appCode.trim().length() != 0) {
            String newMac = mac.replace(":", "").toUpperCase();
            String key = token.token + newMac + token.timestamp;
            try {
                String decryptValue = KeyHelper.decrypt(token.appCode, key);
                token.setDecryptAppCode(decryptValue);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        } else {//此修改属于过度方案，使用默认key
            token.setDecryptAppCode(Key.FIX_KEY);
            return true;
        }
    }
}
