import { consume } from "@lit/context";
import type { LitElement } from "lit";
import { state } from "lit/decorators/state.js";

import { fetchContext } from "../gui/fetchContext.js";

export declare class FetchMixinInterface {
  fetch: typeof fetch;
}

type Constructor<T = {}> = new (...args: any[]) => T;
export function FetchMixin<T extends Constructor<LitElement>>(superClass: T) {
  class FetchElement extends superClass {
    @consume({ context: fetchContext, subscribe: true })
    @state()
    fetch: (url: string, init?: RequestInit) => Promise<Response> =
      fetch.bind(window);
  }

  return FetchElement as Constructor<FetchMixinInterface> & T;
}
