package com.yutou.bilibili.services;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.biliapi.api.LoginApi;
import com.yutou.biliapi.bean.login.LoginCookieDatabaseBean;
import com.yutou.biliapi.bean.login.LoginUserDatabaseBean;
import com.yutou.biliapi.bean.login.QRCodeGenerateBean;
import com.yutou.biliapi.bean.user.UserInfoBean;
import com.yutou.biliapi.databases.BiliBiliLoginDatabase;
import com.yutou.biliapi.net.BiliCookieManager;
import com.yutou.biliapi.net.BiliLoginNetApiManager;
import com.yutou.biliapi.net.BiliUserNetApiManager;
import com.yutou.common.okhttp.HttpBody;
import com.yutou.common.okhttp.HttpCallback;
import com.yutou.common.utils.RedisTools;
import okhttp3.Headers;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

@Service
public class LiveLoginService {
    BiliBiliLoginDatabase loginDatabase;

    public LiveLoginService() {
        loginDatabase = BiliBiliLoginDatabase.getInstance();
    }

    /**
     * loginApi.getQRCodeGenerate().enqueue(new HttpCallback<QRCodeGenerateBean>() {
     *
     * @Override public void onResponse(Headers headers, int code, String status, QRCodeGenerateBean response, String rawResponse) {
     * String oauthKey = response.getQrcode_key();
     * String url = response.getUrl();
     * String bd = "gourl=https%3A%2F%2Fpassport.bilibili.com%2Fajax%2FminiLogin%2Fredirect&oauthKey=" + oauthKey;
     * callback.onResponse(headers, LOGIN_QRCODE, null, null, url);
     * new Thread(() -> waitLogin(oauthKey, callback)).start();
     * }
     * @Override public void onFailure(Throwable throwable) {
     * <p>
     * }
     * });
     */
    public String createQRCode() {
        LoginApi loginApi = BiliLoginNetApiManager.getInstance().getLoginApi();
        try {
            QRCodeGenerateBean data = loginApi.getQRCodeGenerate().execute().body().getData();
            String oauthKey = data.getQrcode_key();
            String url = data.getUrl();
            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void login() {

    }

    public List<LoginUserDatabaseBean> getAllUser() {

        return loginDatabase.getAllUser();
    }

    public List<LoginCookieDatabaseBean> getAllUserCookie() {
        return loginDatabase.getAllCookies();
    }

    public LoginCookieDatabaseBean getCookie(String userId) {
        return loginDatabase.getCookie(userId);
    }

    public JSONObject login(String loginToken) {
        String ret = RedisTools.get(loginToken);
        if (StringUtils.hasText(ret)) {
            JSONObject json = JSONObject.parseObject(ret);
            if (json.getIntValue("code") == BiliLoginNetApiManager.LOGIN_SUCCESS) {
                RedisTools.remove(loginToken);
            }
            return json;
        }
        BiliLoginNetApiManager.getInstance().login(new HttpCallback<LoginCookieDatabaseBean>() {
            @Override
            public void onResponse(Headers headers, int code, String status, LoginCookieDatabaseBean response, String rawResponse) {
                JSONObject json = new JSONObject();
                json.put("code", code);
                if (code == BiliLoginNetApiManager.LOGIN_QRCODE) {
                    json.put("qrcode", rawResponse);
                } else if (code == BiliLoginNetApiManager.LOGIN_SUCCESS) {
                    Response<HttpBody<UserInfoBean>> execute = null;
                    try {
                        execute = BiliUserNetApiManager.getInstance().getUserApi(response).getUserInfo().execute();
                        if (execute.isSuccessful()) {
                            if (execute.body() != null) {
                                UserInfoBean data = execute.body().getData();
                                LoginUserDatabaseBean userBean = new LoginUserDatabaseBean(data);
                                BiliBiliLoginDatabase.getInstance().initData(response, userBean).close();
                                json.put("user", data);
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                RedisTools.set(loginToken, json.toString(), 60);
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
        return null;
    }

    public boolean refreshUserCookie(String uid) {
        return BiliCookieManager.refreshCookie(loginDatabase.getCookie(uid));
    }
}
