using GraphQL.Client;
using GraphQL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;

namespace BodyshopPartner.Utils
{
    public static class GraphQL
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        
        public static GraphQLHttpClient CreateGQLClient()
        {
            var graphQLClient = new GraphQLHttpClient(AppMetaData.graphQlEndpoint, new NewtonsoftJsonSerializer());

            graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + Utils.Auth.authlink.FirebaseToken);
            return graphQLClient;
        }

        public static async Task<dynamic> ExecuteQuery(GraphQLRequest r)
        {
            using (var g = Utils.GraphQL.CreateGQLClient())
            {
                logger.Trace("Firing GQL Query: {0} {1}", r.Query.ToString(), r.Variables);
                var graphQLResponse = await g.SendQueryAsync<dynamic>(r);
                if (graphQLResponse.Errors == null)
                {
                    
                    //logger.Trace("GQL Response: {0}", graphQLResponse.Data);
                    return graphQLResponse.Data;
                }
                else
                {
                    string exceptionString = "";
                    bool jwtExpired = false;
                    logger.Error("Error executing query.");
                    Array.ForEach(graphQLResponse.Errors, x =>
                   {
                       logger.Error(x.Message);
                       if (x.Message.Contains("JWTExpired"))
                       {
                           jwtExpired = true;
                       };
                       exceptionString = exceptionString + x + ";";
                   });
                    if (jwtExpired) await Utils.Auth.Refresh(); ;
                    logger.Error("---------------------");
                    throw new Exception(exceptionString);
                }
            }
        }
    }
}
