import { Plantation } from '../../entities/plantation.entity';
import { PlantationSiteRepository } from '../plantationSite-repository';
import { HttpService } from '@nestjs/axios';
import { from, lastValueFrom, map, Observable, of, subscribeOn } from 'rxjs';
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
// import {
//   FisUASRequestMessage,
//   ResponseMessage,
// } from '../../../CommonMicroserviceModule/message/fis.request.message';
// import { RequestMessage } from 'src/CommonMicroserviceModule/message/fisappmessagejslib/fis/fismessagetype';

import fetcher from 'isomorphic-fetch';
import ApolloBoost, { gql } from 'apollo-boost';
import ApolloClient from 'apollo-boost';
import {
  Block,
  BlockResolvers,
  QueryResolvers,
  QuerySiteArgs,
  Resolvers,
  Site,
  SiteResolvers,
} from 'src/generated/graphql';
import { FisCreateMessageUtility, QueryMessage, ResponseMessage , Query} from "../../../CommonMicroserviceModule/message/FISAppMessageJSUtility/interface/export";

@Injectable()
export class PlantationRepositoryMemoryAdapter extends PlantationSiteRepository {
  constructor(private readonly http: HttpService) {
    super();
  }
  ResponseService: FisCreateMessageUtility;
  QueryService: FisCreateMessageUtility;
  client = new ApolloBoost({
    uri: process.env.GRAPHQL_HOST + '/graphql',
    fetchOptions: { fetch: fetcher },
  });

  GET_SITE = gql`
    query Site($db: String!) {
      site(db: $db) {
        db
        name
        phases {
          sec_code
          sec_desc
          sec_id
          sec_name
          blocks {
            loc_code
            loc_desc
            loc_area
          }
        }
      }
    }
  `;

  GET_SITES = gql`
    query {
      sites {
        db
        name
      }
    }
  `;

  async query(payload: any): Promise<ResponseMessage> {
    
    const data = await this.client.query<SiteResolvers, QuerySiteArgs>({
      query: this.GET_SITE,
      variables: {
        db: payload.data.data.databaseName,
      },
    });

    return this.generateResponseFisMsg('Graphql site response', data);
  }

  async queryAll(): Promise<ResponseMessage> {
    const data = await this.client.query<Query>({
      query: this.GET_SITES,
    });

    return this.generateResponseFisMsg('Graphql All sites response', data);
  }

  generateResponseFisMsg(name, result) {
    if (!this.ResponseService) {
      this.ResponseService = new FisCreateMessageUtility('getResponseMessage');
      this.QueryService = new FisCreateMessageUtility('getQueryMessage');
    }

    let queryMessage = this.QueryService.getQueryMessage('ABC', Query.GetData ,result.data);


    return this.ResponseService.getResponseMessage(
      'ABC_RESPONSE',
      name,
      queryMessage,
    );
  }
}
