/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-inferrable-types */

import { ApolloClient, createHttpLink, gql, HttpLink, from, InMemoryCache } from "@apollo/client";
import { onError } from "@apollo/client/link/error";
import { Observable } from "rxjs";
import { QueryClient } from "./QueryClient";
import fetch from 'cross-fetch';

export class ApolloClientQuery extends QueryClient {

  clientInstance: any
  errorLink = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      console.log(graphQLErrors);

    }

    if (networkError) {
      // handle network error
      console.log(networkError);
    }
  });
  constructor() {

    super();

    // Start apollo client

    this.clientInstance = new ApolloClient({
      link: from([this.errorLink, new HttpLink({ uri: 'http://localhost:3002/graphql', fetch })]),
      cache: new InMemoryCache(),
    });

  }

  sendQuery(queryString: string): Observable<any> {
    let queryObservable: Observable<any>;

    if (this.isCacheOn) {
      queryObservable = new Observable((subscriber) => {

        this.clientInstance.readQuery({
          query: gql`${queryString}`,
        }).then(x => {
          Object.keys(x.data).forEach(y => {
            Object.keys(x.data[y]).forEach(z => {
              if (z != '__typename') {
                subscriber.next(x.data[y][z]);
              }
            })
          })
          subscriber.complete();
        }).catch(error => {
          subscriber.error("error subscribe graphql " + error)
        });
      });

    }
    else {
      queryObservable = new Observable((subscriber) => {

        this.clientInstance.query({
          query: gql`${queryString}`,
        }).then(x => {
          Object.keys(x.data).forEach(y => {
            Object.keys(x.data[y]).forEach(z => {
              if (z != '__typename') {
                subscriber.next(x.data[y][z]);
              }
            })
          })
          subscriber.complete();
        }).catch(error => {
          subscriber.error("error subscribe graphql " + error)
        });
      });

    }
    return queryObservable;

  }
}