import type http from "@ohos:net.http";
import type { Chain } from '../core/Chain';
import UploadRequestBody from "@normalized:N&&&@yic/http/src/main/ets/requestbody/UploadRequestBody&1.0.1";
import type { Interceptor } from './Interceptor';
/**
 * @ProjectName : HarmonyUtilSdk
 * @FileName : LogInterceptor
 * @Author : yic
 * @Time : 2024/6/21 11:16
 * @Description : 日志拦截器
 */
export class LogInterceptor implements Interceptor {
    private index = 0;
    async intercept(chain: Chain): Promise<http.HttpResponse> {
        return new Promise<http.HttpResponse>((resolve, reject) => {
            this.index++;
            let i = this.index;
            let requestBody = chain.requestBody;
            let tmp = requestBody.getUrl();
            console.debug(`[${i} request]`, `${requestBody.getMethod()} ${tmp}`);
            for (let key in requestBody.getHeader()) {
                console.info(`[${i} request header]`, `${key}: ${requestBody.getHeader()[key]}`);
            }
            for (let key in requestBody.getParam()) {
                console.info(`[${i} request param]`, `${key}: ${requestBody.getParam()[key]}`);
            }
            if (requestBody instanceof UploadRequestBody) {
                requestBody.getFiles().forEach((item) => {
                    console.info(`[${i} request file]`, JSON.stringify(item));
                });
            }
            console.debug(`[${i} request]`, 'End');
            return chain.process(chain).then((response) => {
                console.debug(`[${i} response]`, `${response.responseCode} ${requestBody.getMethod()} ${tmp}`);
                for (let key in response.header) {
                    console.info(`[${i} response]`, `${key}: ${response.header[key]}`);
                }
                console.info(`[${i} response]`, JSON.stringify(response.result));
                resolve(response);
            })
                .catch((error) => {
                console.error(`[${i} response]`, JSON.stringify(error));
                reject(error);
            })
                .then(() => {
                console.debug(`[${i} response]`, 'End <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
            });
        });
    }
}
