import { gql } from "graphql-request";
import { DataFetcher } from "../DataFetcher";
export class ResourceFetcher {
  constructor() {
    this.templateByQuery = new Map();
    this.buldTemplates();
  }
  buldTemplates() {
    this.templateByQuery.set("fetchResource", gql `query($name: String!) {
                    $queryAlias$: fetchResource(name: $name){
                        resource
                    }
                  }`);
    this.templateByQuery.set("saveResource", gql `mutation($resource: InputResource!) {
                $queryAlias$: saveResource(resource: $resource){
                    name
                    resource                    
                }
              }`);
  }
  loadResource(name) {
    if (ResourceFetcher._loadingResource.has(name)) {
      return ResourceFetcher._loadingResource.get(name);
    }
    const promiseLoadResource = new Promise((resolve, reject) => {
      DataFetcher.get()
        .callGraphQL({
        values: { name },
        query: this.templateByQuery.get("fetchResource"),
      })
        .then((result) => {
        resolve(result === null || result === void 0 ? void 0 : result.resource);
        ResourceFetcher._loadingResource.delete(name);
      })
        .catch((error) => {
        reject(error);
        ResourceFetcher._loadingResource.delete(name);
      });
    });
    ResourceFetcher._loadingResource.set(name, promiseLoadResource);
    return promiseLoadResource;
  }
  saveResource(resource, name) {
    return new Promise((resolve, reject) => {
      DataFetcher.get()
        .callGraphQL({
        values: {
          resource: {
            name: name,
            resource: JSON.stringify(resource)
          }
        },
        query: this.templateByQuery.get("saveResource")
      })
        .then((resp) => {
        resolve(resp);
      })
        .catch((error) => {
        reject(error);
      });
    });
  }
}
ResourceFetcher._loadingResource = new Map();
