import { MiniProfile } from "../../interface/responseType/MiniProfile";
import CommonUtils from "../utils/CommonUtils";
import Provider from "../provider/Provider";
import ResponseInject from "../../interface/ResponseInject";
import { Injectable } from "../../container/Injectable";
import ClassName from "../../container/ClassName";
import LocalConfigWrapper from "../LocalConfigWrapper";

/**
 * fetch 事件监听回调
 */
@Injectable()
@ClassName("FetchEventCallback")
export default class FetchEventCallback extends Provider implements ResponseInject {
    className = "FetchEventCallback";

    newNode = document.createElement('div')

    constructor(
        private readonly localConfigWrapper: LocalConfigWrapper,
        private readonly commonUtils: CommonUtils,
    ) {
        super();
    }

    /**
     * fetch 返回后处理
     * @param url
     * @param response
     */
    public responseHandler(url: string, response) {
        // mini profile 中添加上次动作
        if (url.startsWith('/profiles.php?step=getMiniProfile&XID=') && this.localConfigWrapper.config.ShowMiniProfLastAct) {
            window.setTimeout(async () => {
                let cont = CommonUtils.querySelector('[class*=profile-mini-_userProfileWrapper___]');
                let resp: MiniProfile = response.json as MiniProfile;
                let formatted = this.commonUtils.secondsFormat(resp.user.lastAction.seconds);

                (await cont).append(this.newNode);
                this.newNode.innerText = '上次动作: ' + formatted;
            }, 0);
        }
    }
}
