using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using Decal.Interop.Net;

namespace Decal.DecalNet
{
    [ComVisible(true)]
    [Guid("15631E36-55CB-4D16-ADE7-74D9F8A5F4B6")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(IWebRequestEvents))]
    [ProgId("DecalNet.WebRequest")]
    public class WebRequestImpl : IWebRequest
    {
        public event IWebRequestEvents_BeginEventHandler Begin;
        public event IWebRequestEvents_EndEventHandler End;

        public void Get(string strURL)
        {
            Begin?.Invoke();
            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    using (var client = new WebClient())
                    {
                        string result = client.DownloadString(strURL);
                        End?.Invoke(200, result);
                    }
                }
                catch (WebException ex)
                {
                    int code = 0;
                    if (ex.Response is HttpWebResponse resp)
                        code = (int)resp.StatusCode;
                    End?.Invoke(code, ex.Message);
                }
                catch (Exception ex)
                {
                    End?.Invoke(0, ex.Message);
                }
            });
        }

        public void Post(string strURL, string strPostData)
        {
            Begin?.Invoke();
            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    using (var client = new WebClient())
                    {
                        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                        string result = client.UploadString(strURL, strPostData);
                        End?.Invoke(200, result);
                    }
                }
                catch (WebException ex)
                {
                    int code = 0;
                    if (ex.Response is HttpWebResponse resp)
                        code = (int)resp.StatusCode;
                    End?.Invoke(code, ex.Message);
                }
                catch (Exception ex)
                {
                    End?.Invoke(0, ex.Message);
                }
            });
        }
    }
}
