package com.yutou.bilibili.BiliBili.Tools;

import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.BiliBili.Datas.BiliBiliUpData;
import com.yutou.bilibili.BiliBili.LiveUtils;
import com.yutou.bilibili.mybatis.Bili.mybatis.model.BilibiliUpInfo;
import com.yutou.bilibili.sqlite.BiliBiliLiveDatabasesManager;
import org.springframework.util.StringUtils;

public class BiliTools {
    public static BilibiliUpInfo checkout(BilibiliUpInfo info) {
        if (StringUtils.isEmpty(info.getUrl())) {
            return null;
        }
        if (!info.getUrl().contains("http")) {
            info.setUrl("https://live.bilibili.com/" + info.getUrl());
        }
        BilibiliUpInfo data = getBiliUpInfo(info.getUrl());
        info.setUrl(data.getUrl());
        info.setRoomid(data.getRoomid());
        info.setName(data.getName());
        return info;
    }

    public static BilibiliUpInfo getBiliUpInfo(String url) {
        if(!url.startsWith("http")){
            url="https://live.bilibili.com/"+url;
        }
        BilibiliUpInfo upData = new BilibiliUpInfo();
        JSONObject json = LiveUtils.http_get("https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id=" + url.replace("https://live.bilibili.com/", "").split("\\?")[0]);
        com.yutou.bilibili.Tools.Log.i(json);
        String roomId = json.getJSONObject("data").getJSONObject("room_info").getInteger("room_id") + "";
        String name = json.getJSONObject("data").getJSONObject("anchor_info").getJSONObject("base_info").getString("uname");
        com.yutou.bilibili.Tools.Log.i(roomId);
        com.yutou.bilibili.Tools.Log.i(name);
        upData.setRoomid(Integer.parseInt(roomId));
        upData.setName(name);
        upData.setUrl(url);
        return upData;
    }
}
