package com.yutou.biliapi.net;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.UserApi;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.user.UserFollowingsBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.bilibili.Controllers.BiliUserController;
import com.yutou.bilibili.services.LiveLoginService;
import com.yutou.common.inter.IHttpApiCheckCallback;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.okhttp.api.BaseApi;
import okhttp3.Headers;

import java.util.HashMap;
import java.util.List;

public class BiliUserNetApiManager extends BaseApi {
    public static final int LOGIN_LOGOUT = 1;

    public static BiliUserNetApiManager manager;

    private BiliUserNetApiManager() {
        super("https://api.bilibili.com");
    }

    public static BiliUserNetApiManager getInstance() {
        if (manager == null) {
            manager = new BiliUserNetApiManager();
        }
        return manager;
    }

    public UserApi getUserApi(LoginCookieDatabaseBean cookie) {
        return getUserApi(cookie, null);
    }

    public UserApi getUserApi(LoginCookieDatabaseBean cookie, HashMap<String, String> addCookie) {
        HashMap<String, String> headers = new HashMap<>();
        StringBuilder ck = new StringBuilder();
        if (cookie != null) {
            JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(cookie));
            for (String key : json.keySet()) {
                ck.append(key).append("=").append(json.getString(key)).append("; ");
            }
        }
        if (addCookie != null) {
            addCookie.forEach((k, v) -> ck.append(k).append("=").append(v).append("; "));
        }
        if(!ck.isEmpty()) {
            headers.put("Cookie", ck.toString());
            setHeaders(headers);
        }
        return createApi(UserApi.class);
    }

    public static void main(String[] args) {
        LiveLoginService loginService = new LiveLoginService();
        LoginCookieDatabaseBean cookie = loginService.getCookie("96300");
        UserApi api = BiliUserNetApiManager.getInstance().getUserApi(cookie);
        api.getFollowings(cookie.getDedeUserID(), "", 50, 1).enqueue(new HttpCallback<UserFollowingsBean>() {
            @Override
            public void onResponse(Headers headers, int code, String status, UserFollowingsBean response, String rawResponse) {
                System.out.println("关注数:" + response.getTotal());
                for (UserFollowingsBean.Follow follow : response.getList()) {
                    System.out.println(follow.getUname());
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
    }
}
