// import { useSWR } from "sswr";
import { derived, type Readable } from "svelte/store";
import { UpListing, UpObject } from "upend";
import type { ListingResult, EntityListing, EntityInfo } from "upend/types";
import { useSWR } from "../util/fetch";
import api from "./api";

export function useEntity(address: string) {
  const { data, error, revalidate } = useSWR<EntityListing, unknown>(
    `${api.apiUrl}/obj/${address}`
  );

  const entity: Readable<UpObject | undefined> = derived(data, ($listing) => {
    if ($listing) {
      const listing = new UpListing($listing.entries);
      return listing.getObject(address);
    }
  });

  const entityInfo: Readable<EntityInfo | undefined> = derived(
    data,
    ($listing) => {
      if ($listing) {
        return $listing.entity;
      }
    }
  );

  return {
    entity,
    entityInfo,
    error,
    revalidate,
  };
}

export function query(query: string) {
  console.debug(`Querying: ${query}`);
  const { data, error, revalidate } = useSWR<ListingResult, unknown>(
    `${api.apiUrl}/query`,
    { method: "POST", body: query }
  );

  const result = derived(data, ($values) => {
    return $values ? new UpListing($values) : undefined;
  });

  return {
    result,
    error,
    revalidate,
  };
}
