package com.yutou.bilibili.Tools;

import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.BiliBili.LiveUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class TestMain {
    public static void main(String[] args) {
        new TestMain();
    }

    public TestMain() {
        try {
            JSONObject cookie = JSONObject.parseObject(LiveUtils.getFile("cookies.json"));
            JSONObject userHear = new JSONObject();
            userHear.put("csrf_token",cookie.getString("bili_jct"));
            userHear.put("csrf",cookie.getString("bili_jct"));
            userHear.put("visit_id","");
            HttpURLConnection connection=LiveUtils.getBiliHttpPost("https://api.live.bilibili.com/User/userOnlineHeart",LiveUtils.getCookie());
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            OutputStream connectionOutputStream = null;
            connectionOutputStream = connection.getOutputStream();
            connectionOutputStream.write(HttpTools.toUrlParams(userHear).getBytes(StandardCharsets.UTF_8));
            connectionOutputStream.flush();
            JSONObject hearBeat;
            hearBeat=LiveUtils.http_post("https://api.live.bilibili.com/User/userOnlineHeart", HttpTools.toUrlParams(userHear));
           /* BufferedInputStream stream = new BufferedInputStream(connection.getInputStream());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0, size;
            while ((len = stream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            String str = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);*/

            com.yutou.bilibili.Tools.Log.i("["+AppTools.getToDayNowTimeToString()+"]"+hearBeat);
        } catch (Exception e) {
            com.yutou.bilibili.Tools.Log.e(e);
        }
    }
    public static int byteArrayToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

}
