package com.yutou.biliapi.net;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LiveApi;
import com.yutou.biliapi.bean.live.LiveAnchorInfo;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.common.okhttp.api.BaseApi;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BiliLiveNetApiManager extends BaseApi {
    private static BiliLiveNetApiManager instance;

    public static BiliLiveNetApiManager getInstance() {
        if (instance == null) {
            instance = new BiliLiveNetApiManager("https://api.live.bilibili.com");
        }
        return instance;
    }

    private BiliLiveNetApiManager(String URL) {
        super(URL);
    }

    public LiveApi getApi(String loginUid) {
        if(StringUtils.hasText(loginUid)) {
            LoginCookieDatabaseBean cookie = BiliBiliLoginDatabase.getInstance().getCookie(loginUid);
            if (cookie != null) {
                useCookie(JSONObject.parseObject(JSONObject.toJSONString(cookie)));
            }
        }
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept-Language", "zh-CN,zh;q=0.8");
        header.put("Referer", "https://live.bilibili.com");
        header.put("Connection", "keep-alive");
        header.put("Upgrade-Insecure-Requests", "1");
        addHeader(header);
        return createApi(LiveApi.class);
    }

    public Map<String, LiveAnchorInfo> getAnchorInfos(String loginUid,List<BigInteger> anchorIds) {
        JSONObject json = new JSONObject();
        json.put("uids", anchorIds);
        try {
            String src = getApi(loginUid).getLiveRoomStatus(json).execute().body().getSrc();
            json = JSONObject.parseObject(src);
            if (json.getInteger("code") == 0) {
                Map<String, LiveAnchorInfo> map = new HashMap<>();
                JSONObject data = json.getJSONObject("data");
                for (String key : data.keySet()) {
                    LiveAnchorInfo info = JSONObject.parseObject(data.getString(key), LiveAnchorInfo.class);
                    map.put(key, info);
                }
                return map;
            }
            return new HashMap<>();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

    }
}
