package com.skyversation.poiaddr.addquery;

import com.alibaba.fastjson.JSONObject;
import com.skyversation.poiaddr.bean.WDToken;
import com.skyversation.poiaddr.util.net.AddressNetTools;
import com.skyversation.poiaddr.bean.AddressResult;
import com.skyversation.poiaddr.util.status.AddressResultEnum;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AddressTools {

    private static AddressTools instance = new AddressTools();
    private AddressTools(){}
    public synchronized static AddressTools getInstance(){
        if(instance == null){
            instance = new AddressTools();
        }
        return instance;
    }

    public WDToken getWDToken(String userName, String pwd){
        long time = System.currentTimeMillis() / 1000;
        System.out.println("当前时间为：" + time);
        String secret = time + pwd;
        System.out.println("当前secret为：" + secret);
        secret = md5_32(secret);
        System.out.println("加密后secret为：" + secret);

        String param = "?user=" + userName + "&secret=" + secret + "&time=" + time;
        System.out.println("准备获取token，获取地址为：" + Constant.GET_TOKEN_URL + param);
        ResponseEntity responseEntity =AddressNetTools.getInstance().requestGetOrPost(HttpMethod.GET,Constant.GET_TOKEN_URL + param, null, null,0);
        if(responseEntity != null){
            String body = responseEntity.getBody() + "";
            WDToken wdToken = JSONObject.parseObject(body, WDToken.class);
            System.out.println("获取token完成，返回信息为：" + body);
            return wdToken;
        }else{
            return null;
        }
    }

    private String md5_32(String msg){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(msg.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public AddressResult faildQuery(AddressResultEnum code, String message){
        return new AddressResult(code, message);
    }

}
