namespace TeamViewerApi.TeamViewer.Rest
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    public class Connection
    {
        private Properties properties;

        public Connection(Properties properties)
        {
            this.properties = properties;
        }

        /// <summary>
        /// Send request
        /// </summary>
        /// <returns>Result of the request</returns>
        public string SendRequest()
        {
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(this.properties.URL);
            webReq.ContentType = this.properties.ContentType;
            webReq.Method = this.properties.Method.ToString();
            webReq.Headers.Add("Authorization", string.Format("Bearer {0}", this.properties.AccessToken));

            if ((webReq.Method == WebRequestMethods.Http.Post || webReq.Method == WebRequestMethods.Http.Put) && !string.IsNullOrEmpty(this.properties.PostData))
            {
                var postBytes = Encoding.UTF8.GetBytes(this.properties.PostData);
                webReq.ContentLength = postBytes.Length;

                Stream stream = webReq.GetRequestStream();
                stream.Write(postBytes, 0, postBytes.Length);
                stream.Close();
            }

            string result = string.Empty;

            try
            {
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();

                using (Stream stream = response.GetResponseStream())
                    if (stream != null)
                        using (StreamReader streamReader = new StreamReader(stream))
                            result = streamReader.ReadToEnd();
            }
            catch (WebException ex)
            {
                System.Diagnostics.Debug.WriteLine("{0:hh:mm:ss} TeamViewer.Rest.SendRequest: {1} {2} => {3}", DateTime.Now, this.properties.Method.ToString(), this.properties.URL, ex.Message);
            }

            return result;
        }
    }
}
