import AjaxFetchOption from "../../interface/AjaxFetchOption";
import IUserProfileData from "../../interface/IUserProfileData";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
import Logger from "../Logger";

@ClassName('FetchUtils')
@Injectable()
export default class FetchUtils {
    constructor(
        private readonly logger: Logger,
    ) {
    }

    /**
     * 包装jquery ajax 异步返回string
     * @param url
     * @param method
     */
    public ajax(url: string, method: 'GET' | 'POST'): Promise<string> {
        return new Promise((res, rej) => {
            $.ajax({
                method: method,
                url: url,
                success: function (data) {
                    res(data)
                },
                error: function (e) {
                    rej(e)
                }
            });
        });
    }

    /**
     * jquery ajax 方法发送的 xhr, 头部中带有 X-Requested-With: XMLHttpRequest
     * return fetch
     * @param opt
     * @param opt.url 必输
     * @param opt.referrer 默认: /
     * @param opt.method POST|GET 必输
     * @param opt.body ?
     */
    public ajaxFetch(opt: AjaxFetchOption) {
        let { url, referrer = '/', method, body = null } = opt;
        let req_params: RequestInit = {
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            referrer,
            method,
        };
        if (method === 'POST') {
            req_params.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            req_params.body = body;
        }
        return window.fetch(url, req_params);
    }

    public fetchText(url: string, init: RequestInit = null): Promise<string> {
        return new Promise((resolve, reject) =>
            window.fetch(url, init)
                .then(res => res.text())
                .then(t => resolve(t))
                .catch(err => {
                    this.logger.error('fetchText出错了', err);
                    reject(err);
                })
        );
    }

    public getProfile(uid: string): Promise<IUserProfileData> {
        return new Promise((resolve, reject) => {
            this.ajaxFetch({
                url: window.addRFC('https://www.torn.com/profiles.php?step=getProfileData&XID=' + uid),
                method: 'GET'
            }).then((o) => {
                o.json().then((res) => {
                    resolve(res);
                }).catch(e => {
                    this.logger.error('[ProfileHelper] JSON解析错误: ', e.message, '错误堆栈: ', e.stack);
                    reject(e);
                });
            }).catch(e => {
                this.logger.error('[ProfileHelper] 网络错误: ', e.message, '错误堆栈: ', e.stack);
                reject(e);
            });
        });
    }
}
