package com.yutou.qqbot.utlis;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;

public class XiaoMiRouter {
    private final static String key = "a2ffa5c9be07488bbb04a3a47d3c5f6a";
    private static String token = null;

    public static void setNotToken() {
        token = null;
    }

    public static String getToken() {
        if (token != null) {
            return token;
        }
        String nonce = nonceCreat();
        String oldPwd = DigestUtils.sha1Hex(nonce + DigestUtils.sha1Hex("34864394" + key));
        JSONObject json = new JSONObject();
        json.put("username", "admin");
        json.put("password", oldPwd);
        json.put("logtype", 2);
        json.put("nonce", nonce);
        json = JSONObject.parseObject(HttpTools.http_post("http://192.168.31.1/cgi-bin/luci/api/xqsystem/login", HttpTools.toUrlParams(json).getBytes(StandardCharsets.UTF_8), 1, null));
        if (json.getInteger("code") == 0) {
            token = json.getString("token");
            return token;
        }
        return null;
    }

    public static String getDeviceListUrl() {
        return "http://192.168.31.1/cgi-bin/luci/;stok=" + getToken() + "/api/misystem/devicelist";
    }

    private static String nonceCreat() {
        return String.format("%s_%s_%s_%s", 0, HttpTools.getLocalMacAddress(), (int) (System.currentTimeMillis() / 1000), (int) (Math.random() * 10000));
    }

    public static void main(String[] args) {
        String url = XiaoMiRouter.getDeviceListUrl();
        JSONObject json = JSONObject.parseObject(HttpTools.get(url));
        System.out.println("json = " + json);
    }
}