<commit_before>﻿using System;
using System.Net.Http;
using System.Reflection;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Refit;

using Camunda.Api.Client.CaseDefinition;
using Camunda.Api.Client.CaseExecution;
using Camunda.Api.Client.CaseInstance;
using Camunda.Api.Client.DecisionDefinition;
using Camunda.Api.Client.Deployment;
using Camunda.Api.Client.Execution;
using Camunda.Api.Client.ExternalTask;
using Camunda.Api.Client.Group;
using Camunda.Api.Client.History;
using Camunda.Api.Client.Incident;
using Camunda.Api.Client.Job;
using Camunda.Api.Client.JobDefinition;
using Camunda.Api.Client.Message;
using Camunda.Api.Client.Migration;
using Camunda.Api.Client.ProcessDefinition;
using Camunda.Api.Client.ProcessInstance;
using Camunda.Api.Client.Signal;
using Camunda.Api.Client.Tenant;
using Camunda.Api.Client.User;
using Camunda.Api.Client.UserTask;
using Camunda.Api.Client.VariableInstance;

using JsonSerializer = Newtonsoft.Json.JsonSerializer;

namespace Camunda.Api.Client
{
    public class CamundaClient
    {
        private Lazy<ICaseDefinitionRestService> _caseDefinitionRestService;
        private Lazy<ICaseExecutionRestService> _caseExecutionRestService;
        private Lazy<ICaseInstanceRestService> _caseInstanceRestService;
        private Lazy<IDecisionDefinitionRestService> _decisionDefinitionRestService;
        private Lazy<IDeploymentRestService> _deploymentApi;
        private Lazy<IExecutionRestService> _executionApi;
        private Lazy<IExternalTaskRestService> _externalTaskApi;
        private Lazy<IGroupRestService> _groupApi;
        private Lazy<IIncidentRestService> _incidentApi;
        private Lazy<IJobDefinitionRestService> _jobDefinitionApi;
        private Lazy<IJobRestService> _jobApi;
        private Lazy<IMigrationRestService> _migrationRestService;
        private Lazy<IMessageRestService> _messageApi;
        private Lazy<IProcessDefinitionRestService> _processDefinitionApi;
        private Lazy<IProcessInstanceRestService> _processInstanceApi;
        private Lazy<ISignalRestService> _signalApi;
        private Lazy<ITenantRestService> _tenantApi;
        private Lazy<IUserRestService> _userApi;
        private Lazy<IUserTaskRestService> _userTaskApi;
        private Lazy<IVariableInstanceRestService> _variableInstanceApi;

        private HistoricApi _historicApi;

        private string _hostUrl;
        private HttpClient _httpClient;

        private RefitSettings _refitSettings;
        private HttpMessageHandler _httpMessageHandler;
        internal static JsonSerializerSettings JsonSerializerSettings { get; private set; }
        internal static IContentSerializer JsonContentSerializer { get; private set; }

        internal class HistoricApi
        {
            public Lazy<IHistoricActivityInstanceRestService> ActivityInstanceApi;
            public Lazy<IHistoricCaseActivityInstanceRestService> CaseActivityInstanceApi;
            public Lazy<IHistoricCaseDefinitionRestService> CaseDefinitionApi;
            public Lazy<IHistoricCaseInstanceRestService> CaseInstanceApi;
            public Lazy<IHistoricDecisionInstanceRestService> DecisionInstanceApi;
            public Lazy<IHistoricDetailRestService> DetailApi;
            public Lazy<IHistoricIncidentRestService> IncidentApi;
            public Lazy<IHistoricJobLogRestService> JobLogApi;
            public Lazy<IHistoricProcessInstanceRestService> ProcessInstanceApi;
            public Lazy<IHistoricVariableInstanceRestService> VariableInstanceApi;
        }

        static CamundaClient()
        {
            JsonSerializerSettings = JsonSerializerSettings ?? new JsonSerializerSettings
            {
                ContractResolver = new CustomCamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore, // do not send empty fields
            };

            JsonSerializerSettings.Converters.Add(new StringEnumConverter());
            JsonSerializerSettings.Converters.Add(new CustomIsoDateTimeConverter());

            JsonContentSerializer = JsonContentSerializer ?? new JsonContentSerializer(JsonSerializerSettings);
        }

        private class CustomIsoDateTimeConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
        {
            public CustomIsoDateTimeConverter()
            {
                Culture = CultureInfo.InvariantCulture;
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                if (value is DateTime dateTime)
                {
                    if ((DateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                        || (DateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    {
                        dateTime = dateTime.ToUniversalTime();
                    }

                    writer.WriteValue(dateTime.ToJavaISO8601());
                }
                else
                {
                    base.WriteJson(writer, value, serializer);
                }
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                bool nullable = objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable<>);

                if (reader.TokenType == JsonToken.String)
                {
                    string dateText = reader.Value.ToString();

                    if (string.IsNullOrEmpty(dateText) && nullable)
                        return null;

                    if (dateText.EndsWith("UTC"))
                    {
                        if (DateTime.TryParseExact(dateText.Replace("UTC", "Z"), "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dt))
                            return dt;
                    }
                }

                return base.ReadJson(reader, objectType, existingValue, serializer);
            }
        }

        private void Initialize()
        {
            _httpMessageHandler = _httpMessageHandler ?? new ErrorMessageHandler();

            _refitSettings = _refitSettings ?? new RefitSettings
            {
                ContentSerializer = JsonContentSerializer,
                UrlParameterFormatter = new CustomUrlParameterFormatter(),
                HttpMessageHandlerFactory = () => _httpMessageHandler
            };
        }

        private class CustomUrlParameterFormatter : DefaultUrlParameterFormatter
        {
            public override string Format(object parameterValue, ICustomAttributeProvider attributeProvider, Type type)
            {
                if (parameterValue is bool)
                    return string.Format(CultureInfo.InvariantCulture, "{0}", parameterValue).ToLowerInvariant();

                return base.Format(parameterValue, attributeProvider, type);
            }
        }

        private class CustomCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
        {
            // preserve exact dictionary key
            protected override string ResolveDictionaryKey(string dictionaryKey) => dictionaryKey;
        }

        private CamundaClient(string hostUrl)
        {
            _hostUrl = hostUrl;
            Initialize();
            CreateServices();
        }

        private CamundaClient(HttpClient httpClient)
        {
            _httpClient = httpClient;
            Initialize();
            CreateServices();
        }

        private CamundaClient(string hostUrl, HttpMessageHandler httpMessageHandler)
        {
            _hostUrl = hostUrl;
            _httpMessageHandler = httpMessageHandler;
            Initialize();
            CreateServices();
        }

        private void CreateServices()
        {
            _caseDefinitionRestService = CreateService<ICaseDefinitionRestService>();
            _caseExecutionRestService = CreateService<ICaseExecutionRestService>();
            _decisionDefinitionRestService = CreateService<IDecisionDefinitionRestService>();
            _deploymentApi = CreateService<IDeploymentRestService>();
            _executionApi = CreateService<IExecutionRestService>();
            _externalTaskApi = CreateService<IExternalTaskRestService>();
            _groupApi = CreateService<IGroupRestService>();
            _incidentApi = CreateService<IIncidentRestService>();
            _jobApi = CreateService<IJobRestService>();
            _jobDefinitionApi = CreateService<IJobDefinitionRestService>();
            _messageApi = CreateService<IMessageRestService>();
            _migrationRestService = CreateService<IMigrationRestService>();
            _processDefinitionApi = CreateService<IProcessDefinitionRestService>();
            _processInstanceApi = CreateService<IProcessInstanceRestService>();
            _signalApi = CreateService<ISignalRestService>();
            _tenantApi = CreateService<ITenantRestService>();<commit_msg>Fix missing instantiation of ICaseInstanceRestService<commit_after>﻿using System;
using System.Net.Http;
using System.Reflection;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Refit;

using Camunda.Api.Client.CaseDefinition;
using Camunda.Api.Client.CaseExecution;
using Camunda.Api.Client.CaseInstance;
using Camunda.Api.Client.DecisionDefinition;
using Camunda.Api.Client.Deployment;
using Camunda.Api.Client.Execution;
using Camunda.Api.Client.ExternalTask;
using Camunda.Api.Client.Group;
using Camunda.Api.Client.History;
using Camunda.Api.Client.Incident;
using Camunda.Api.Client.Job;
using Camunda.Api.Client.JobDefinition;
using Camunda.Api.Client.Message;
using Camunda.Api.Client.Migration;
using Camunda.Api.Client.ProcessDefinition;
using Camunda.Api.Client.ProcessInstance;
using Camunda.Api.Client.Signal;
using Camunda.Api.Client.Tenant;
using Camunda.Api.Client.User;
using Camunda.Api.Client.UserTask;
using Camunda.Api.Client.VariableInstance;

using JsonSerializer = Newtonsoft.Json.JsonSerializer;

namespace Camunda.Api.Client
{
    public class CamundaClient
    {
        private Lazy<ICaseDefinitionRestService> _caseDefinitionRestService;
        private Lazy<ICaseExecutionRestService> _caseExecutionRestService;
        private Lazy<ICaseInstanceRestService> _caseInstanceRestService;
        private Lazy<IDecisionDefinitionRestService> _decisionDefinitionRestService;
        private Lazy<IDeploymentRestService> _deploymentApi;
        private Lazy<IExecutionRestService> _executionApi;
        private Lazy<IExternalTaskRestService> _externalTaskApi;
        private Lazy<IGroupRestService> _groupApi;
        private Lazy<IIncidentRestService> _incidentApi;
        private Lazy<IJobDefinitionRestService> _jobDefinitionApi;
        private Lazy<IJobRestService> _jobApi;
        private Lazy<IMigrationRestService> _migrationRestService;
        private Lazy<IMessageRestService> _messageApi;
        private Lazy<IProcessDefinitionRestService> _processDefinitionApi;
        private Lazy<IProcessInstanceRestService> _processInstanceApi;
        private Lazy<ISignalRestService> _signalApi;
        private Lazy<ITenantRestService> _tenantApi;
        private Lazy<IUserRestService> _userApi;
        private Lazy<IUserTaskRestService> _userTaskApi;
        private Lazy<IVariableInstanceRestService> _variableInstanceApi;

        private HistoricApi _historicApi;

        private string _hostUrl;
        private HttpClient _httpClient;

        private RefitSettings _refitSettings;
        private HttpMessageHandler _httpMessageHandler;
        internal static JsonSerializerSettings JsonSerializerSettings { get; private set; }
        internal static IContentSerializer JsonContentSerializer { get; private set; }

        internal class HistoricApi
        {
            public Lazy<IHistoricActivityInstanceRestService> ActivityInstanceApi;
            public Lazy<IHistoricCaseActivityInstanceRestService> CaseActivityInstanceApi;
            public Lazy<IHistoricCaseDefinitionRestService> CaseDefinitionApi;
            public Lazy<IHistoricCaseInstanceRestService> CaseInstanceApi;
            public Lazy<IHistoricDecisionInstanceRestService> DecisionInstanceApi;
            public Lazy<IHistoricDetailRestService> DetailApi;
            public Lazy<IHistoricIncidentRestService> IncidentApi;
            public Lazy<IHistoricJobLogRestService> JobLogApi;
            public Lazy<IHistoricProcessInstanceRestService> ProcessInstanceApi;
            public Lazy<IHistoricVariableInstanceRestService> VariableInstanceApi;
        }

        static CamundaClient()
        {
            JsonSerializerSettings = JsonSerializerSettings ?? new JsonSerializerSettings
            {
                ContractResolver = new CustomCamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore, // do not send empty fields
            };

            JsonSerializerSettings.Converters.Add(new StringEnumConverter());
            JsonSerializerSettings.Converters.Add(new CustomIsoDateTimeConverter());

            JsonContentSerializer = JsonContentSerializer ?? new JsonContentSerializer(JsonSerializerSettings);
        }

        private class CustomIsoDateTimeConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
        {
            public CustomIsoDateTimeConverter()
            {
                Culture = CultureInfo.InvariantCulture;
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                if (value is DateTime dateTime)
                {
                    if ((DateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                        || (DateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                    {
                        dateTime = dateTime.ToUniversalTime();
                    }

                    writer.WriteValue(dateTime.ToJavaISO8601());
                }
                else
                {
                    base.WriteJson(writer, value, serializer);
                }
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                bool nullable = objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable<>);

                if (reader.TokenType == JsonToken.String)
                {
                    string dateText = reader.Value.ToString();

                    if (string.IsNullOrEmpty(dateText) && nullable)
                        return null;

                    if (dateText.EndsWith("UTC"))
                    {
                        if (DateTime.TryParseExact(dateText.Replace("UTC", "Z"), "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFK", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out var dt))
                            return dt;
                    }
                }

                return base.ReadJson(reader, objectType, existingValue, serializer);
            }
        }

        private void Initialize()
        {
            _httpMessageHandler = _httpMessageHandler ?? new ErrorMessageHandler();

            _refitSettings = _refitSettings ?? new RefitSettings
            {
                ContentSerializer = JsonContentSerializer,
                UrlParameterFormatter = new CustomUrlParameterFormatter(),
                HttpMessageHandlerFactory = () => _httpMessageHandler
            };
        }

        private class CustomUrlParameterFormatter : DefaultUrlParameterFormatter
        {
            public override string Format(object parameterValue, ICustomAttributeProvider attributeProvider, Type type)
            {
                if (parameterValue is bool)
                    return string.Format(CultureInfo.InvariantCulture, "{0}", parameterValue).ToLowerInvariant();

                return base.Format(parameterValue, attributeProvider, type);
            }
        }

        private class CustomCamelCasePropertyNamesContractResolver : CamelCasePropertyNamesContractResolver
        {
            // preserve exact dictionary key
            protected override string ResolveDictionaryKey(string dictionaryKey) => dictionaryKey;
        }

        private CamundaClient(string hostUrl)
        {
            _hostUrl = hostUrl;
            Initialize();
            CreateServices();
        }

        private CamundaClient(HttpClient httpClient)
        {
            _httpClient = httpClient;
            Initialize();
            CreateServices();
        }

        private CamundaClient(string hostUrl, HttpMessageHandler httpMessageHandler)
        {
            _hostUrl = hostUrl;
            _httpMessageHandler = httpMessageHandler;
            Initialize();
            CreateServices();
        }

        private void CreateServices()
        {
            _caseDefinitionRestService = CreateService<ICaseDefinitionRestService>();
            _caseExecutionRestService = CreateService<ICaseExecutionRestService>();
            _caseInstanceRestService = CreateService<ICaseInstanceRestService>();
            _decisionDefinitionRestService = CreateService<IDecisionDefinitionRestService>();
            _deploymentApi = CreateService<IDeploymentRestService>();
            _executionApi = CreateService<IExecutionRestService>();
            _externalTaskApi = CreateService<IExternalTaskRestService>();
            _groupApi = CreateService<IGroupRestService>();
            _incidentApi = CreateService<IIncidentRestService>();
            _jobApi = CreateService<IJobRestService>();
            _jobDefinitionApi = CreateService<IJobDefinitionRestService>();
            _messageApi = CreateService<IMessageRestService>();
            _migrationRestService = CreateService<IMigrationRestService>();
            _processDefinitionApi = CreateService<IProcessDefinitionRestService>();
            _processInstanceApi = CreateService<IProcessInstanceRestService>();
            _signalApi = CreateService<ISignalRestService>();
            _tenantApi = CreateService<ITenantRestService>();
{'fraction_non_alphanumeric': 0.06763074915733391, 'fraction_numerical': 0.0005436555398499511, 'mean_word_length': 2.7012072434607646, 'pattern_counts': {'":': 0, '<': 98, '<?xml version=': 0, '>': 102, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '504919', 'n_tokens_mistral': 4383, 'n_tokens_neox': 4236, 'n_words': 821}