using System;
using System.IO;
using System.Net;
using DataMatch.AddressVerification.Contracts;
using DataMatch.AddressVerification.Entities;
using DataMatch.AddressVerification.Helpers;

namespace DataMatch.AddressVerification
{
    public class CassManager : ICassManager
    {
        /// <summary>
        /// Should be created just using the factory.
        /// </summary>
        internal CassManager()
        {
        }

        /// <summary>
        /// Returns an array of first 5 address suggestions by incomplete primary address.
        /// </summary>
        /// <param name="cassRequest"> Contains primary address to lookup (String field ICassRequest.Query). </param>
        /// <returns> Array of entities with suggestions. Every item contains Country, City, State, etc. details. </returns>
        public ICassResponses GetAddressSuggestions(ICassRequest cassRequest)
        {
            String responseString = GetAddressSuggestionsInternal(cassRequest);
            return JsonHelper.Deserialize<CassResponses>(responseString);
        }

        /// <summary>
        /// Returns first 5 address suggestions by incomplete primary address as JSON.
        /// </summary>
        /// <param name="primaryAddress"> String with incomplete primary address. </param>
        /// <returns> JSON with 5 address suggestions. </returns>
        public String GetAddressSuggestions(String primaryAddress)
        {
            ICassRequest cassRequest = new CassRequest(primaryAddress);
            return GetAddressSuggestionsInternal(cassRequest);
        }

        private String GetAddressSuggestionsInternal(ICassRequest cassRequest)
        {
            String responseString;

            String uri = RequestHelper.GetRequestString(cassRequest);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream stream = response.GetResponseStream())
            {
                if (stream != null)
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        responseString = reader.ReadToEnd();
                    }
                }
                else
                {
                    responseString = String.Empty;
                }
            }

            return responseString;
        }
    }
}
