<commit_before>﻿using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using RemoteArduino.Commands;
using Repsaj.Submerged.GatewayApp.Universal.Exceptions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Repsaj.Submerged.GatewayApp.Device
{
    class AzureConnection : IAzureConnection
    {
        public event ICommandReceived CommandReceived;
        public event Action Connected;
        public event Action Disconnected;

        string _deviceConnectionString;
        JsonSerializerSettings _settings;
        DeviceClient _deviceClient;

        bool _connected = false;

        public AzureConnection(string IoTHubHostname, string deviceId, string deviceKey)
        {
            string deviceConnectionString = $"HostName={IoTHubHostname};DeviceId={deviceId};SharedAccessKey={deviceKey}";          

            // Initialize the device client object which is used to connect to Azure IoT hub
            // Create the IoT Hub Device Client instance
            _deviceConnectionString = deviceConnectionString;

            // use camlCasing for json objects
            _settings = new JsonSerializerSettings();
            _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // create the device client for Azure
            _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionString);
        }
        
        private async Task TestConnection()
        {
            try
            {
                var message = new Microsoft.Azure.Devices.Client.Message();

                await _deviceClient.SendEventAsync(message);

                SetConnected();
            }
            catch (Exception ex) when (ex.Message.Contains("UnauthorizedException"))
            {
                SetDisconnected();
                throw new DeviceNotAuthorizedException();
            }
            catch (Exception ex) when (ex.Message.Contains("DeviceNotFound"))
            {
                SetDisconnected();
                throw new DeviceNotFoundException();
            }

        }
        public async Task Init()
        {
            await TestConnection();

            // start listening for Cloud 2 Device messages 
            ReceiveC2dAsync();
        }

        private void SetDisconnected()
        {
            if (_connected)
            {
                _connected = false;
                Disconnected?.Invoke();
            }
        }

        private void SetConnected()
        {
            if (!_connected)
            {
                _connected = true;
                Connected?.Invoke();
            }
        }

        /// <summary>
        /// Sends an event to the IoT Hub
        /// </summary><commit_msg>Added one additional catch for other exceptions<commit_after>﻿using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using RemoteArduino.Commands;
using Repsaj.Submerged.GatewayApp.Universal.Exceptions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Repsaj.Submerged.GatewayApp.Device
{
    class AzureConnection : IAzureConnection
    {
        public event ICommandReceived CommandReceived;
        public event Action Connected;
        public event Action Disconnected;

        string _deviceConnectionString;
        JsonSerializerSettings _settings;
        DeviceClient _deviceClient;

        bool _connected = false;

        public AzureConnection(string IoTHubHostname, string deviceId, string deviceKey)
        {
            string deviceConnectionString = $"HostName={IoTHubHostname};DeviceId={deviceId};SharedAccessKey={deviceKey}";          

            // Initialize the device client object which is used to connect to Azure IoT hub
            // Create the IoT Hub Device Client instance
            _deviceConnectionString = deviceConnectionString;

            // use camlCasing for json objects
            _settings = new JsonSerializerSettings();
            _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // create the device client for Azure
            _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionString);
        }
        
        private async Task TestConnection()
        {
            try
            {
                var message = new Microsoft.Azure.Devices.Client.Message();

                await _deviceClient.SendEventAsync(message);

                SetConnected();
            }
            catch (Exception ex) when (ex.Message.Contains("UnauthorizedException"))
            {
                SetDisconnected();
                throw new DeviceNotAuthorizedException();
            }
            catch (Exception ex) when (ex.Message.Contains("DeviceNotFound"))
            {
                SetDisconnected();
                throw new DeviceNotFoundException();
            }
            catch (Exception ex)
            {
                SetDisconnected();
                throw ex;
            }
        }
        public async Task Init()
        {
            await TestConnection();

            // start listening for Cloud 2 Device messages 
            ReceiveC2dAsync();
        }

        private void SetDisconnected()
        {
            if (_connected)
            {
                _connected = false;
                Disconnected?.Invoke();
            }
        }

        private void SetConnected()
        {
            if (!_connected)
            {
                _connected = true;
                Connected?.Invoke();
            }
        }

        /// <summary>
        /// Sends an event to the IoT Hub
        /// </summary>
{'fraction_non_alphanumeric': 0.07261924409968641, 'fraction_numerical': 0.0006601749463607857, 'mean_word_length': 1.8666035950804163, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, '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': '3522567', 'n_tokens_mistral': 1405, 'n_tokens_neox': 1357, 'n_words': 361}