using System.Text;
using System.Net;
using System.IO;
using pcmp.Setting;

namespace pcmp
{
    public static class Net
    {
        public static string GetStringFromHttp(string url, Encoding enc, out HttpStatus httpStatus)
        {
            httpStatus = new HttpStatus();
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
            webReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            webReq.UserAgent = "Mozilla/4.0 (PeerCastMultiPlayer2)";
            switch (Settings.GeneralSetting.NetworkSetting.HttpProtocol)
            {
                case 0: webReq.ProtocolVersion = HttpVersion.Version11; break;
                case 1: webReq.ProtocolVersion = HttpVersion.Version10; break;
                default: webReq.ProtocolVersion = HttpVersion.Version11; break;
            }

            if (Settings.GeneralSetting.NetworkSetting.UseProxy)
            {
                if (Settings.GeneralSetting.NetworkSetting.UseIEProxy)
                    webReq.Proxy = HttpWebRequest.GetSystemWebProxy();
                else
                    webReq.Proxy = new WebProxy(Settings.GeneralSetting.NetworkSetting.ProxyAddr);
            }
            webReq.Timeout = Settings.GeneralSetting.NetworkSetting.TimeOut;
            Stream st = null;
            StreamReader sr = null;
            HttpWebResponse res = null;
            string html;
            try
            {
                res = (HttpWebResponse)webReq.GetResponse();
                st = res.GetResponseStream();
                sr = new StreamReader(st, enc);
                html = sr.ReadToEnd();
                httpStatus.StatusCode = ((int)res.StatusCode).ToString();
                httpStatus.StatusDesc = res.StatusDescription;
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    httpStatus.StatusCode = ((int)((HttpWebResponse)e.Response).StatusCode).ToString()
                        + ((HttpWebResponse)e.Response).StatusCode.ToString();
                    httpStatus.StatusDesc = ((HttpWebResponse)e.Response).StatusDescription;
                }
                else
                {
                    httpStatus.StatusCode = "none";
                    httpStatus.StatusDesc = e.Message;
                }
                html = null;
            }
            finally
            {
                if (res != null) res.Close();
                if (st != null) st.Close();
                if (sr != null) sr.Close();
            }
            return html;
        }
    }

    public class HttpStatus
    {
        public string StatusCode = string.Empty;
        public string StatusDesc = string.Empty;
    }
}
