import {IApi} from "./IApi";
import {IApiParamsCollection} from "./IApiParamsCollection";
import {ApiHandler} from "./ApiHandler";
import {
    ExpectFunction,
    FailFunction,
    ResolveParams,
    ResponseHandlerDefineFunction,
    SuccessFunction
} from "./TypeDefine";
import {AxiosInstance} from "axios";
import {ISendResponse} from "./ISendResponse";

class ApiHandlerFetch<T extends IApi> extends ApiHandler<T> {
    config: RequestInit

    constructor(api: T, responseHandlerDefineFunction: ResponseHandlerDefineFunction, config: RequestInit) {
        super(api, responseHandlerDefineFunction);
        this.config = config;
    }

    send(args: ResolveParams<T["params"]>): Promise<ISendResponse<any>> {
        if (!this.api.path) return Promise.reject(`request path is undefined`)
        const init: RequestInit = {...this.config};

        let path = this.api.path;
        init.method = this.api.method;

        if (Array.isArray(this.api.params)) {
            const params = ApiHandler.assemblyParameters(this.api.params, args, this.api);
            if (typeof params === 'string')
                path += params
            else
                init.body = JSON.stringify(params);
        } else if (typeof this.api.params !== 'undefined') {
            const params = ApiHandler.assemblyParametersToUnion(this.api.params, args, this.api);
            path += params.path + params.query
            init.body = JSON.stringify(params.body);
        }
        return fetch(path, init)
            .then(r => r.json())
            .then(res=>{
                const response: ISendResponse<T> = {
                    code: res.code ?? res.status ?? 200,
                    message: res.message ?? res.msg ?? "成功",
                    data: res.data
                }
                return response;
            });

    }


}

export {ApiHandlerFetch}