import { Interceptors } from "../types/Interceptors";
import InterceptorsManager from "../types/InterceptorsManager";

class InterceptorRunner {
  interceptors:Interceptors
  constructor() {
    this.interceptors = {
      before: new InterceptorsManager(),
      after:new InterceptorsManager(),
    };
  }
  
  /**
   * 请求
   * @param config 请求参数
   * @returns 
   */
  request(config:any,handler?:Function){
    const h=(res:any)=>{
      return res;
    }
    const missionQuery = [handler||h, undefined];
    // 推入队列都是一对的，代表成功和失败的回调函数
    this.interceptors.before.handlers.forEach((interceptor) => {
      missionQuery.unshift(interceptor.fulfilled, interceptor.rejected);
    });
    this.interceptors.after.handlers.forEach((interceptor) => {
      missionQuery.push(interceptor.fulfilled, interceptor.rejected);
    });
    let promise = Promise.resolve(config);
    while (missionQuery.length > 0) {
      //then第一个参数是处理成功的参数，第二个是处理失败的参数(类似于catch的简便写法)
      promise = <Promise<Object>>promise.then(missionQuery.shift(), missionQuery.shift());
    }
    return promise;
  }
  /**
   * get请求
   * @param url 
   * @param opts 
   * @returns 
   */
  run(str:any,callback?:Function){
    return this.request( str,callback);
  }
}
export default InterceptorRunner