package basic.taobaotv.util;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import basic.taobaotv.config.TaobaotvConfig;


/**
 * Created by fanwang on 10/8/16.
 */
public class TaobaotvUtil {
    private static final SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 生成tvmall的url地址
     * @param user_id  用户id
     * @param user_token 用户token
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getTvmallUrl( String user_id,String user_token) throws UnsupportedEncodingException {
        String charset = TaobaotvConfig.CharSet;

        String tvmall_url = TaobaotvConfig.TVMALL_URL;
        String app_secret = TaobaotvConfig.APP_SECRET;

        Map<String, String> param = new TreeMap<String, String>();
        Map<String, String> sign_param = new TreeMap<String, String>();
        sign_param.put("app_key", TaobaotvConfig.APPKEY);
        sign_param.put("user_id", user_id);

        sign_param.put("expired_time", getCurrentTime());

        sign_param.put("user_token", user_token);
        sign_param.put("backurl", TaobaotvConfig.BACK_URL);
        sign_param.put("redirect_to", TaobaotvConfig.REDIRECT_TO);

        ////////////////////////////////签名过程
        StringBuilder sign = new StringBuilder();
        sign_method(app_secret, param, sign_param, sign);
        param.putAll(sign_param);

        //////////////////////////////////生成请求路径
        String url = getReqPath(charset, tvmall_url, param);
        return url;
    }

    /**
     * 获取当前时间
     * @return
     */
    private static String getCurrentTime() {
        synchronized (TIME_FORMATTER) {
            return TIME_FORMATTER.format(new Date());
        }
    }

    /**
     * 生成签名内容
     * @param app_secret
     * @param param
     * @param sign_param
     * @param sign
     */
    private static void sign_method(String app_secret,Map<String, String> param, Map<String, String> sign_param,StringBuilder sign) {
        sign.append(app_secret);

        Iterator<Map.Entry<String, String>> ite = sign_param.entrySet().iterator();
        while (ite.hasNext()) {
            Map.Entry<String, String> me = ite.next();
            String key = me.getKey();
            String value = me.getValue();
            sign.append(key).append(value);
        }
        sign.append(app_secret);
        String str = byte2hex(md5(sign.toString())).toUpperCase();
        param.put("sign", str);
    }

    /**
     * md5编码
     * @param plainText
     * @return
     */
    private static byte[] md5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            return md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * 根据请求参数生成请求路径
     * @param charset  字符集
     * @param tvmall_url 电视淘宝的url
     * @param param 请求参数
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String getReqPath(String charset, String tvmall_url,Map<String, String> param) throws UnsupportedEncodingException {
        StringBuilder url = new StringBuilder();
        url.append(tvmall_url);

        Iterator<Map.Entry<String, String>> ite = param.entrySet().iterator();
        boolean first = true;
        while (ite.hasNext()) {
            Map.Entry<String, String> me = ite.next();
            String key = me.getKey();
            String value = me.getValue();

            if (first) {
                url.append("?").append(key).append("=").append(URLEncoder.encode(value, charset));
                first = false;
            } else {
                url.append("&").append(key).append("=").append(URLEncoder.encode(value, charset));
            }
        }
        return url.toString();
    }
}
