using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace ExWeb
{
    public static class Http
    {
        public static Stream ReadUri(string Path)
        {
            Uri uri;
            try
            {
                uri = new Uri(Path);
            }
            catch
            {
                return null;
            }
            WebRequest wReq = WebRequest.Create(Path);
            WebResponse wResp;
            try
            {
                wResp = wReq.GetResponse();
            }
            catch
            {
                return null;
            }
            Stream respStream = wResp.GetResponseStream();
            return respStream;
        }
        public static string StripHtml(string HtmlPage)
        {
            if (HtmlPage.ToLower().Contains("id=\"form1\"")) // aspx
            {
                Regex r = new Regex("</form>.*", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
                r = new Regex("<!DOCTYPE(.*?)<form(.*?)>", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
                r = new Regex("<html(.*?)<form(.*?)>", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
            }
            else
            {
                Regex r = new Regex("</body>.*", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
                r = new Regex("<!DOCTYPE(.*?)<body(.*?)>", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
                r = new Regex("<html(.*?)<body(.*?)>", RegexOptions.Singleline);
                HtmlPage = r.Replace(HtmlPage, "");
            }
            return HtmlPage;
        }
        public static string GetStream(Stream s)
        {
            const int maxBytes = 1024;
            string CodeToInsert = "";
            byte[] b = new byte[maxBytes];
            int BytesRead = s.Read(b, 0, b.Length);
            while (BytesRead > 0)
            {
                CodeToInsert += System.Text.Encoding.UTF8.GetString(b, 0, BytesRead);
                BytesRead = s.Read(b, 0, b.Length);
            }
            return CodeToInsert;
        }
    }
}