import { HttpService } from '@nestjs/axios';

import { Injectable } from '@nestjs/common';
// import {
//   FisQueryMessage,
//   FisUASRequestMessage,
//   ResponseMessage,
// } from '../../../CommonMicroserviceModule/message/fis.request.message';

import fetcher from 'isomorphic-fetch';
import ApolloBoost, { gql } from 'apollo-boost';
import {

  DataServiceResolvers,
  QueryDataserviceArgs,

} from '../../../generated/graphql';
import { FisAppRepository } from '../fisapp-repository';
import axios from 'axios';
import { FisCreateMessageUtility, QueryMessage, ResponseMessage , Query} from "../../../CommonMicroserviceModule/message/FISAppMessageJSUtility/interface/export";
import { Observable } from 'rxjs';

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

  GET_DATASERVICE = gql`
    query dataservice($className: String!, 
                      $filter: String!,
                      $returnFormatType: String!) {
      dataservice(className: $className, filter: $filter, returnFormatType: $returnFormatType) {
        filter,
        className,
        returnFormatType,
        returnSequenceTotal,
        returnSequenceNumber,
        data
        
      }
    }
  `;

  query(payload: any): Observable<any> {
      let result = [];
  


      return new Observable((subscriber) => {
   
        const obs = this.http.post(`${process.env.GRAPHQL_HOST}/graphql`,{ query: `${payload.data.payload}`})
        obs.subscribe({
          next: (x)=>{
            Object.keys(x.data.data).forEach(y=>{
              Object.keys(x.data.data[y]).forEach(z=>{
                subscriber.next(x.data.data[y][z])
              })
            })
          },
          error: (e)=>{
            subscriber.error("error subscribe graphql "+ e)
          },
          complete: ()=>{
            subscriber.complete();
          }
        })
      })



          // await axios({
          //   url: 'http://localhost:3002/graphql',
          //   method: 'POST',
          //   data: {
          //     query: `${payload.data.data.payload}`}
          // }).then(r=>{
          //   resolve(r.data.data)
          // }).catch(error=>{
          //   reject(error)
          // });
      // })

      // return new Observable((subscriber)=>{
      //     const srv = new HttpService();
      //     const obs = srv.post('http://localhost:3002/graphql', {query: `${payload.data.data.payload}`})

      //     obs.subscribe({
      //       next: (x)=>{
      //         let convertedData = {};
      //         convertedData = x.data;
      //         result.push(convertedData);
              
      //       }
      //     })
      // })

      // return new Promise((resolve, reject)=>{
      //   this.client.query({
      //     query: gql`query dataservice( className: "APAccountProfileDataService" filter: "" ) { className  filter returnFormatType  returnSequenceTotal  returnSequenceNumber   data  } `,
      //    }).then(result=>{    
      //      console.log(result)   
      //      console.log(result.data)
      //    }).catch(error=>{
      //      reject(error)
      //    });
      //  })

      // return new Promise((resolve, reject)=>{  //http apollo-boost
      //  this.client.query<DataServiceResolvers, QueryDataserviceArgs>({
      //     query: this.GET_DATASERVICE,
      //     variables: {
      //       className: payload.data.data.className,
      //       filter: payload.data.data.filter? payload.data.data.filter: "",
      //       returnFormatType: payload.data.data.returnFormatType ? payload.data.data.returnFormatType: "full"
      //     },
      //   }).then(result=>{       
      //     resolve(result.data)
      //   }).catch(error=>{
      //     reject(error)
      //   });
      // })
      // return this.generateResponseFisMsg('Graphql site response',payload, data);
      
  }


  generateResponseFisMsg(name, request, result) {
    if (!this.ResponseService) {
      this.ResponseService = new FisCreateMessageUtility('getResponseMessage');
      this.QueryService = new FisCreateMessageUtility('getQueryMessage');
    }
    // let queryMessage = this.QueryService.getQueryMessage('ABC', 'QUERY' ,result.data);
    let queryMessage: QueryMessage = request.data;
    

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