using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
using Rac.Tools;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mime;
using System.Text;

namespace Rac.Models
{
    internal class Response
    {
        public HttpStatusCode StatusCode { get; set; }

        public string StatusDescription { get; set; }

        public WebHeaderCollection Headers { get; set; }

        public byte[] Body { get; set; }

        public string ContentType => Headers?["content-type"];

        public bool GetHtmlDocument(out IHtmlDocument html)
        {
            var contentType = ContentType;
            if (null == contentType)
            {
                html = null;
                return false;
            }

            var ct = new ContentType(contentType);
            if (ct.MediaType != "text/html")
            {
                html = null;
                return false;
            }

            using var stream = new MemoryStream(Body);
            var doc = new HtmlParser().ParseDocument(stream);
            html = doc;
            return true;
        }

        public HttpHeader[] GetServerTimeHeaders()
        {
            var lst = new List<HttpHeader>(2);

            var last = Headers?["last-modified"];
            var date = Headers?["date"];

            if (false == string.IsNullOrEmpty(last)) lst.Add(new HttpHeader("last-modified", last));
            if (false == string.IsNullOrEmpty(date)) lst.Add(new HttpHeader("date", date));

            return lst.ToArray();
        }

        public bool GetCss(out string css)
        {
            var contentType = ContentType;
            if (null == contentType)
            {
                css = null;
                return false;
            }

            var ct = new ContentType(contentType);
            if (ct.MediaType != "text/css")
            {
                css = null;
                return false;
            }

            var enc = Encoding.GetEncoding(ct.CharSet ?? "utf-8");
            css = enc.GetString(Body);
            return true;
        }

        public bool GetRedirect(out string redirectUrl)
        {
            if (false == StatusCode.In(HttpStatusCode.TemporaryRedirect, HttpStatusCode.Redirect, HttpStatusCode.Moved))
            {
                redirectUrl = null;
                return false;
            }
            redirectUrl = Headers["location"];
            return true;
        }
    }
}