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

export type EntityInfo =
  | {
      t: "Hash" | "Uuid";
    }
  | {
      t: "Attribute" | "Url";
      c: string;
    };

export interface EntityListing {
  entity: EntityInfo;
  entries: ListingResult;
}

export function useEntity(address: string) {
  const { data, error, revalidate } = useSWR<EntityListing, unknown>(
    `${API_URL}/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_URL}/query`,
    { method: "POST", body: query }
  );

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

  return {
    result,
    error,
    revalidate,
  };
}
