import api from "../lib/api";
import { i18n } from "../i18n";
import { derived, readable, type Readable } from "svelte/store";

const databaseAttributeLabels: Readable<{ [key: string]: string }> = readable(
  {},
  (set) => {
    const result = {};
    api.fetchAllAttributes().then((attributes) => {
      attributes.forEach((attribute) => {
        if (attribute.labels.length) {
          result[attribute.name] = attribute.labels.sort()[0];
        }
      });
      set(result);
    });
  }
);

export const attributeLabels: Readable<{ [key: string]: string }> = derived(
  [i18n, databaseAttributeLabels],
  ([i18n, attributeLabels]) => {
    const result = {};
    Object.assign(result, i18n.getResourceBundle(i18n.language, "attributes"));
    Object.assign(result, attributeLabels);
    return result;
  }
);
