using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using ZuluFeedsSampleApp.Configuration;

namespace ZuluFeedsSampleApp.Sender
{
    public class FeedsRequestSender
    {
        /// <summary>
        /// Utility class used to send request for feeds stream to the trading server provided
        /// using basic http authentication
        /// </summary>
        public static WebResponse sendRequest(ZuluTradingServerConfig config, ZuluTradeAuthenticationInfo authenticationInfo, String feedsRequest){
            WebResponse webResponse = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(config.TradingServicesUrl + feedsRequest);
                String encoding = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationInfo.ZuluAccountUsername + ":" + authenticationInfo.ZuluAccountPassword));
                String authorizationHeader = string.Format("{0} {1}", "Basic", encoding);
                request.Method = "GET";
                request.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                request.ContentType = "text/event-stream; charset=UTF-8";
                webResponse = request.GetResponse();
                return webResponse;
            }
            catch (WebException e) {
                var statusCode = ((HttpWebResponse)e.Response).StatusCode;
                var statusDescription = ((HttpWebResponse)e.Response).StatusDescription;
                Console.WriteLine("Exception when sending Feeds Request :"+statusCode+", message: "+statusDescription);
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when sending Feeds Request :" + e.Message);
                return null;
            }
        }
    }
}
