﻿using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web;
using LinkFuture.Extensions;
using LinkFuture.Library;

namespace LinkFuture.ClientTiming.Web
{
    //reference of Har format
    //http://www.softwareisHard.com/blog/Har-12-spec/
    //https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/Har/Overview.html
    public class ExportHarResource:DBWebContentResource
    {
        public static string HarVersion = DefaultSetting.GetCallingVersion();
        public ExportHarResource(ResourceInfo currentResource) : base(currentResource)
        {

        }
        public override object ReteriveResource(ContentItemInfo content, ContentParameterCollection parameters)
        {
            base.ResetParameters(parameters);
            using (var sql = new SqlHelper(this.Meta.ConnectionString()))
            {
                sql.Command.CommandText = this.Meta.CommamdText;
                sql.Command.CommandType = CommandType.StoredProcedure;
                sql.Command.FindParameters();

                //build BuildSqlParameters
                base.BuildSqlParameters(sql.Command.Parameters, parameters);
                var log = new HarLogInfo(); //sql.SqlRead.Fill<HarLogInfo>();
                log.Version = "1.2";
                log.Creator = new HarCreatorInfo { Name = "LinkFuture.ClientTiming", Version = HarVersion };
                log.Comment = "this har is generaged by LinkFuture Client Timing";

                log.Pages = (List<HarPageInfo>)sql.SqlRead.FillList<HarPageInfo>();

                if (sql.SqlRead.NextResult())
                {
                    log.Browser = sql.SqlRead.Fill<HarBrowserInfo>();
                }

                if (sql.SqlRead.NextResult())
                {
                    log.Entries = (List<HarEntryInfo>)sql.SqlRead.FillList<HarEntryInfo>();
                }
                //hard code for fake use har viewer tool
                log.Pages[0].Id = "page_0";
                foreach (var entry in log.Entries)
                {
                    entry.Pageref = log.Pages[0].Id;
                    entry.Request.Method = "GET";
                    entry.Request.HttpVersion = "HTTP/1.1";
                    entry.Request.Headers = new List<HarHeaderInfo>();
                    entry.Request.Cookies = new List<HarCookieInfo>();
                    entry.Request.QueryString = new List<HarQueryStringInfo>();
                    entry.Request.HeaderSize = -1;
                    entry.Request.BodySize = -1;
                    var url = entry.Request.Url.ToUri();
                    if (url != null)
                    {
                        var queryList = url.Query();
                        if (queryList != null)
                        {
                            foreach (var key in queryList.Keys)
                            {
                                entry.Request.QueryString.Add(new HarQueryStringInfo
                                {
                                    Name = key,
                                    Value = queryList[key]
                                });
                            }
                        }
                    }


                    entry.Response = new HarResponseInfo
                        {
                            Status = 200,
                            Headers = new List<HarHeaderInfo>(),
                            Cookies = new List<HarCookieInfo>(),
                            StatusText = "OK",
                            HeaderSize = -1,
                            BodySize = -1,
                            HttpVersion = "HTTP/1.1",
                            Content = new HarResponseContentInfo {MimeType = "", Size = 0}
                        };
                }
                
                var logs = new HarInfo { Log = log };
                return logs;
            }
            //return base.ReteriveResource(content, parameters);
        }
    }

    public class ExportHarHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var logID = context.Request.QueryString["logID"];
            if(string.IsNullOrWhiteSpace(logID))
            {
                context.Response.Write("Invalid log id");
                context.Response.End();
                return;
            }
            var content = WebContentRender.RenderContentItem("ExportHar", new Dictionary<string, string>
                                                                              {
                                                                                  {"type","Json"},
                                                                                  {"TimingLogID",logID}
                                                                              });
            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + logID + ".har");
            context.Response.AddHeader("Content-Length", content.Length.ToString(CultureInfo.InvariantCulture));
            context.Response.ContentType = "application/octet-stream";
            context.Response.Write(content);
            context.Response.End();
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}