<commit_before>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cosential.Integrations.Compass.Client.Contexts;
using Cosential.Integrations.Compass.Client.Exceptions;
using Cosential.Integrations.Compass.Client.Models;
using Cosential.Integrations.Compass.Contexts;
using RestSharp;
using RestSharp.Authenticators;

namespace Cosential.Integrations.Compass.Client
{
    public class CompassClient : IDisposable
    {
        private readonly RestClient _client;

        public static readonly Uri DefaultUri = new Uri("https://compass.cosential.com/api");
        public readonly JsonSerializer Json;

        public PersonnelContext PersonnelContext => new PersonnelContext(this);
        public CompanyContext CompanyContext => new CompanyContext(this);
        public OfficeContext OfficeContext => new OfficeContext(this);
        public DivisionContext DivisionContext => new DivisionContext(this);
        public StudioContext StudioContext => new StudioContext(this);
        public TerritoryContext TerritoryContext => new TerritoryContext(this);
        public PracticeAreaContext PracticeAreaContext => new PracticeAreaContext(this);
        public OfficeDivisionContext OfficeDivisionContext => new OfficeDivisionContext(this);
        public OpportunityContext OpportunityContext => new OpportunityContext(this);
        public ContactContext ContactContext => new ContactContext(this);
        public ProjectContext ProjectContext => new ProjectContext(this);

        public CompassClient(int firmId, Guid apiKey, string username, string password, Uri host= null)
        {
            if (host == null) host = DefaultUri;

            Json = new JsonSerializer();

            _client = new RestClient(host)
            {
                Authenticator = new HttpBasicAuthenticator(username, password)
                
            };

            _client.ClearHandlers();

            _client.AddDefaultHeader("x-compass-api-key", apiKey.ToString());
            _client.AddDefaultHeader("x-compass-firm-id", firmId.ToString());
            _client.AddDefaultHeader("Accept", "application/json");
            _client.AddDefaultHeader("x-compass-show-error", "true");
            
            _client.AddHandler("application/json", Json);
            _client.AddHandler("text/json", Json);
            _client.AddHandler("text/x-json", Json);
            _client.AddHandler("text/javascript", Json);
            _client.AddHandler("*+json", Json);
        }

        public bool IsAuth()
        {
            var user = GetAuthenticatedUser();
            return (user != null);
        }
        public AuthenticatedUser GetAuthenticatedUser()
        {
            try
            {
                var request = NewRequest("user");
                var result = Execute<List<AuthenticatedUser>>(request);
                return result.Data.FirstOrDefault();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public List<T> GetSubItems<T>(PrimaryEntityType entityType, int entityId, string subitem)
        {
            var request = NewRequest("{entityType}/{id}/{subitem}");
            request.AddUrlSegment("entityType", entityType.ToPlural());
            request.AddUrlSegment("id", entityId.ToString());
            request.AddUrlSegment("subitem", subitem);

            var results = Execute<List<T>>(request);

            return results.Data;
        }

        public RestRequest NewRequest(string resource, Method method = Method.GET)
        {
            var request = new RestRequest(resource, method)
            {
                RequestFormat = DataFormat.Json,
                JsonSerializer = Json
            };

            return request;

        }

        public IRestResponse Execute(RestRequest request)
        {
            var res = _client.Execute(request);
            ValidateResponse(res);
            return res;
        }

        public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
        {
            var res = _client.Execute<T>(request);
            ValidateResponse(res);
            return res;
        }

        public async Task<IRestResponse<T>> ExecuteAsync<T>(RestRequest request, CancellationToken cancel)
        {
            var res = await _client.ExecuteTaskAsync<T>(request, cancel);
            ValidateResponse(res);
            return res;
        }

        public async Task<IRestResponse> ExecuteAsync(RestRequest request, CancellationToken cancel)
        {
            var res = await _client.ExecuteTaskAsync(request, cancel);
            ValidateResponse(res);
            return res;
        }

        private static void ValidateResponse(IRestResponse response)
        {
            if (response.ErrorException != null) throw new HttpResponseException($"Exception in http response from [{response.ResponseUri}]", response.ErrorException);

            //Any success
            if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300) return;

            //404 isn't always an error, sometimes we are checking for existence and 404 is valid
            if (response.StatusCode == HttpStatusCode.NotFound) return;

            throw new ResponseStatusCodeException(response);
        }

        public void Dispose()<commit_msg>Removed response code validation from global validation method<commit_after>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cosential.Integrations.Compass.Client.Contexts;
using Cosential.Integrations.Compass.Client.Exceptions;
using Cosential.Integrations.Compass.Client.Models;
using Cosential.Integrations.Compass.Contexts;
using RestSharp;
using RestSharp.Authenticators;

namespace Cosential.Integrations.Compass.Client
{
    public class CompassClient : IDisposable
    {
        private readonly RestClient _client;

        public static readonly Uri DefaultUri = new Uri("https://compass.cosential.com/api");
        public readonly JsonSerializer Json;

        public PersonnelContext PersonnelContext => new PersonnelContext(this);
        public CompanyContext CompanyContext => new CompanyContext(this);
        public OfficeContext OfficeContext => new OfficeContext(this);
        public DivisionContext DivisionContext => new DivisionContext(this);
        public StudioContext StudioContext => new StudioContext(this);
        public TerritoryContext TerritoryContext => new TerritoryContext(this);
        public PracticeAreaContext PracticeAreaContext => new PracticeAreaContext(this);
        public OfficeDivisionContext OfficeDivisionContext => new OfficeDivisionContext(this);
        public OpportunityContext OpportunityContext => new OpportunityContext(this);
        public ContactContext ContactContext => new ContactContext(this);
        public ProjectContext ProjectContext => new ProjectContext(this);

        public CompassClient(int firmId, Guid apiKey, string username, string password, Uri host= null)
        {
            if (host == null) host = DefaultUri;

            Json = new JsonSerializer();

            _client = new RestClient(host)
            {
                Authenticator = new HttpBasicAuthenticator(username, password)
                
            };

            _client.ClearHandlers();

            _client.AddDefaultHeader("x-compass-api-key", apiKey.ToString());
            _client.AddDefaultHeader("x-compass-firm-id", firmId.ToString());
            _client.AddDefaultHeader("Accept", "application/json");
            _client.AddDefaultHeader("x-compass-show-error", "true");
            
            _client.AddHandler("application/json", Json);
            _client.AddHandler("text/json", Json);
            _client.AddHandler("text/x-json", Json);
            _client.AddHandler("text/javascript", Json);
            _client.AddHandler("*+json", Json);
        }

        public bool IsAuth()
        {
            var user = GetAuthenticatedUser();
            return (user != null);
        }
        public AuthenticatedUser GetAuthenticatedUser()
        {
            try
            {
                var request = NewRequest("user");
                var result = Execute<List<AuthenticatedUser>>(request);
                return result.Data.FirstOrDefault();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public List<T> GetSubItems<T>(PrimaryEntityType entityType, int entityId, string subitem)
        {
            var request = NewRequest("{entityType}/{id}/{subitem}");
            request.AddUrlSegment("entityType", entityType.ToPlural());
            request.AddUrlSegment("id", entityId.ToString());
            request.AddUrlSegment("subitem", subitem);

            var results = Execute<List<T>>(request);

            return results.Data;
        }

        public RestRequest NewRequest(string resource, Method method = Method.GET)
        {
            var request = new RestRequest(resource, method)
            {
                RequestFormat = DataFormat.Json,
                JsonSerializer = Json
            };

            return request;

        }

        public IRestResponse Execute(RestRequest request)
        {
            var res = _client.Execute(request);
            ValidateResponse(res);
            return res;
        }

        public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
        {
            var res = _client.Execute<T>(request);
            ValidateResponse(res);
            return res;
        }

        public async Task<IRestResponse<T>> ExecuteAsync<T>(RestRequest request, CancellationToken cancel)
        {
            var res = await _client.ExecuteTaskAsync<T>(request, cancel);
            ValidateResponse(res);
            return res;
        }

        public async Task<IRestResponse> ExecuteAsync(RestRequest request, CancellationToken cancel)
        {
            var res = await _client.ExecuteTaskAsync(request, cancel);
            ValidateResponse(res);
            return res;
        }

        private static void ValidateResponse(IRestResponse response)
        {
            if (response.ErrorException != null) throw new HttpResponseException($"Exception in http response from [{response.ResponseUri}]", response.ErrorException);
//            //Any success
//            if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300) return;
//
//            //404 isn't always an error, sometimes we are checking for existence and 404 is valid
//            if (response.StatusCode == HttpStatusCode.NotFound) return;
//
//            throw new ResponseStatusCodeException(response);
        }

        public void Dispose()
{'fraction_non_alphanumeric': 0.0910251732944181, 'fraction_numerical': 0.0021889821233126595, 'mean_word_length': 2.3707347064248387, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 55, 'https://': 2, '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': '2682369', 'n_tokens_mistral': 2675, 'n_tokens_neox': 2593, 'n_words': 638}