import { EntityPathReplace } from '@/config';
import { Environment } from '@/environment';
import { logger } from '../utils';
import { ProxyMiddleware } from './proxy-middleware';

/**
 * 实体请求代理中间件
 *
 * @author chitanda
 * @date 2021-12-14 17:12:46
 * @export
 * @abstract
 * @class EntityProxyMiddleware
 * @extends {ProxyMiddleware}
 */
export abstract class EntityProxyMiddleware extends ProxyMiddleware {
  use(req: any, res: any, next: () => void): void {
    if (Environment.EnableRuntime) {
      const url = req.originalUrl;
      const urls = url.split('?');
      // 分割后的旧路径
      const oldUrls = urls[0].split('/');
      // 准备拼接的新路径
      const newUrls: string[] = [];
      for (let i = 0; i < oldUrls.length; i++) {
        const str = oldUrls[i];
        if (!str || str === '') {
          newUrls.push(str);
        } else if (Environment.BasePath.endsWith(str)) {
          newUrls.push(str);
          const attachPaths = Environment.DefaultAPI.Path.split('/');
          attachPaths.forEach(path => {
            if (path) {
              newUrls.push(path);
            }
          });
        } else if (i % 2 === 0) {
          const newName = EntityPathReplace[str];
          if (newName) {
            newUrls.push(newName);
          } else {
            newUrls.push(str);
          }
        } else {
          newUrls.push(str);
        }
      }
      urls[0] = newUrls.join('/');
      const newUrl = urls.join('?');
      logger.debug(`${url} => ${newUrl}`);
      req.originalUrl = newUrl;
    }
    super.use(req, res, next);
  }
}
