/**
 * 模拟浏览器端 Headers 类的实现
 */
export default class CustomHeader implements Headers {
  private headers: Map<string, string>;

  constructor(headers: Record<string, string>) {
    this.headers = new Map(
      Object.keys(headers).map((key) => [key.toLowerCase(), headers[key]])
    );
  }

  get(name: string): string | null {
    return this.headers.get(name.toLowerCase()) ?? null;
  }

  set(name: string, value: string): void {
    this.headers.set(name.toLowerCase(), value);
  }

  has(name: string): boolean {
    return this.headers.has(name.toLocaleLowerCase());
  }

  append(name: string, value: string): void {
    this.set(name, value);
  }

  delete(name: string): void {
    this.headers.delete(name.toLowerCase());
  }

  values() {
    return this.headers.values();
  }

  entries() {
    return this.headers.entries();
  }

  keys() {
    return this.headers.keys();
  }

  forEach(
    callbackfn: (value: string, key: string, map: Headers) => void,
    thisArg?: any
  ) {
    return this.headers.forEach((v, k) => {
      callbackfn.call(thisArg ?? this, v, k, this);
    }, this);
  }

  [Symbol.iterator]() {
    return this.headers[Symbol.iterator]();
  }
}
