using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace NightscoutLibrary.Configuration
{
    public class MonoCompatibleNightscoutAlertConfiguration : INightscoutAlertConfiguration
    {
        private String _nightscoutBaseURL;
        public string APISecretKey { get; set; }

        public MonoCompatibleNightscoutAlertConfiguration(String NightscoutBaseURL, String APISecretKey)
        {
            this.NightscoutBaseURL = NightscoutBaseURL;
            this.APISecretKey = APISecretKey;
        }
        public string NightscoutBaseURL
        {
            get { return _nightscoutBaseURL; }
            set
            { 
                _nightscoutBaseURL = value;
                ResolveHostnameFromURL();
            }
        }


        private void ResolveHostnameFromURL()
        { //Convert any hostname notation into ip-address form to avoid Websocket4Net mono issue regarding hostnames
            Uri nightscoutUri = new Uri(_nightscoutBaseURL);
            String nightscoutHost = nightscoutUri.DnsSafeHost;
            var hostInfo = Dns.GetHostEntry(nightscoutHost);
            if(hostInfo.AddressList == null || !hostInfo.AddressList.Any())
                throw new ApplicationException("An error occurred while resolving the Nightscout server address");
            IPAddress address = hostInfo.AddressList.First();
            _nightscoutBaseURL = _nightscoutBaseURL.Replace(nightscoutHost, address.ToString());
        }
    }
}
