﻿using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using Raspberry.UWP.Models;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace Raspberry.UWP.Services
{
    public class IoTHubService
    {
        public IoTHubService(
            string connectionString)
        {
            _connectionString = connectionString;

            _deviceClient = DeviceClient.CreateFromConnectionString(
                connectionString, 
                Settings.Instance.DeviceId);

        }

        DeviceClient _deviceClient;

        string _connectionString;

        public async Task<bool> SendMessage(Person person)
        {
            try
            {
                //var telemetryDataPoint = new
                //{
                //    deviceId = Settings.Instance.DeviceId,
                //    customMessage = messageText

                //};

                var telemetryDataPoint = new
                {
                    deviceId = Settings.Instance.DeviceId,
                    age = person.Age,
                    anger = person.Anger,
                    contempt = person.Contempt,
                    disgust = person.Disgust,
                    fear = person.Fear,
                    gender = person.Gender,
                    happiness = person.Happiness,
                    neutral = person.Neutral,
                    sadness = person.Sadness,
                    surprise = person.Surprise,
                    specialCommand = person.SpecialCommand
                };

                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message = new Message(Encoding.ASCII.GetBytes(messageString));

                await _deviceClient.SendEventAsync(message);

                return true;
            }
            catch(Exception exc)
            {
                Debug.WriteLine(exc.Message);
                return false;
            }
        }
    }
}
