using FI.FIC;
using Foresight.Fleet.Services.AssetHealth;
using Foresight.Fleet.Services.AssetHealth.WorkOrder;
using Foresight.Fleet.Services.Inspection;
using Foresight.Fleet.Services.JobSite;
using IronIntel.Contractor.FilterQ;
using IronIntel.Contractor.Maintenance;
using IronIntel.Contractor.Site.JobSite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static IronIntel.Contractor.Site.JobSite.JobSiteRequirementsBasePage;

namespace IronIntel.Contractor.Site
{
    public class PrintBasePage : ContractorBasePage
    {
        protected string ProcessRequest()
        {
            int printType = -1;
            string pt = Request.Params["pt"];
            if (!int.TryParse(pt, out printType))
                return "";

            string result = "";
            switch (printType)
            {
                case (int)PrintType.WorkOrder:
                    result = PrintWorkOrder();
                    break;
                case (int)PrintType.DispatchRequest:
                    result = PrintDispatchRequest();
                    break;
                case (int)PrintType.Attachment:
                    PrintAttachment();
                    break;
            }

            return result;
        }

        protected void PrintAttachment()
        {
            string at = Request.Params["at"];
            string attaid = Request.Params["id"];

            byte[] content = null;
            string ext = "";
            string contentType = "application/octet-stream";
            try
            {
                var session = GetCurrentLoginSession();
                if (at == "1" || at == "2")
                {
                    long aid = 0;
                    if (!long.TryParse(attaid, out aid))
                        return;
                    var client = FleetServiceClientHelper.CreateClient<WorkOrderProvider>(SystemParams.CompanyID, GetCurrentLoginSession().SessionID);
                    Tuple<string, byte[]> atta = null;
                    if (at == "1")
                    {
                        atta = client.GetAssetAttachmentData(SystemParams.CompanyID, aid);
                        FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "AssetAttachment", "", "Print", atta.Item1, "", atta.Item2);
                    }

                    else
                    {
                        atta = client.GetWorkOrderAttachmentData(SystemParams.CompanyID, aid);
                        FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "WorkOrderAttachment", "", "Print", atta.Item1, "", atta.Item2);
                    }

                    if (atta != null)
                    {
                        content = atta.Item2;
                        ext = atta.Item1;
                    }
                }
                else if (at == "3")
                {
                    var client = FleetServiceClientHelper.CreateClient<AssetInspectClient>(SystemParams.CompanyID, GetCurrentLoginSession().SessionID);
                    var atta = client.DownloadMediaContent(SystemParams.CompanyID, attaid);
                    FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "MediaContent", "", "DownLoad", "", atta.FileType, atta.Content);
                    if (atta != null)
                    {
                        content = atta.Content;
                        ext = atta.FileType;
                    }
                }
                if (!Helper.FileTypes.TryGetValue(ext, out contentType))
                    ext = Helper.GetFileExtention(ext);
                if (!Helper.FileTypes.TryGetValue(ext, out contentType))
                    contentType = "application/octet-stream";
            }
            catch (Exception ex)
            {
                SystemParams.WriteLog("Error", "PrintAttachment", ex.Message, ex.ToString());
            }
            Response.ContentType = contentType;
            Response.BinaryWrite(content);
            Response.End();
        }

        private string DownloadString(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            return DownloadString(request);
        }

        private string DownloadString(HttpWebRequest request)
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream str = response.GetResponseStream())
            {
                using (StreamReader r = new StreamReader(str))
                {
                    string s = r.ReadToEnd();
                    response.Close();
                    return s;
                }
            }
        }

        private string PrintWorkOrder()
        {
            string woidstr = Request.Params["wo"];
            long woid = -1;
            if (!long.TryParse(woidstr, out woid) || woid <= 0)
                return "";

            var session = GetCurrentLoginSession();
            string html = WorkOrderManager.GenerateWorkOrderPrintHtml(GetCurrentLoginSession().SessionID, SystemParams.CompanyID, woid, GetLanguageCookie());
            FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "WorkOrder", "", "Print", "", "", null);
            return html;
        }

        private string PrintDispatchRequest()
        {
            int type = -1;
            string pt = Request.Params["t"];
            if (!int.TryParse(pt, out type))
                return "";

            string data = Request.Params["ids"];
            long[] ids = JsonConvert.DeserializeObject<long[]>(data);
            if (ids == null || ids.Length == 0)
                return "";

            string assignto = System.Web.HttpUtility.HtmlDecode(Request.Params["assignto"]);

            var client = FleetServiceClientHelper.CreateClient<JobSiteDispatchProvider>(SystemParams.CompanyID, GetCurrentLoginSession().SessionID);

            JobSiteAssetDispatchInfo[] items = null;
            if (type == 0)//create requiremetn
            {
                items = client.GetAssetDispatchsByRequirementIds(SystemParams.CompanyID, ids);
            }
            else//dispatch
            {
                items = client.GetAssetDispatchsByIds(SystemParams.CompanyID, ids);
            }

            if (items == null || items.Length == 0)
                return "";

            string html = GenerateDispatchPrintHtml(GetLanguageCookie(), items, assignto);
            var session = GetCurrentLoginSession();
            FICHostEnvironment.WriteExportAuditTrail(session.User.UID, "Dispatch", "", "Print", "", "", null);
            return html;
        }

        public static string GenerateDispatchPrintHtml(string lang, JobSiteAssetDispatchInfo[] dispatchs, string assignto)
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("<H1 style='text-align:center;'>" + SystemParams.GetTextByKey(lang, "P_JS_DISPATCHREQUESTS", "Dispatch Requests") + "</H1>");
            if (!string.IsNullOrEmpty(assignto))
                str.AppendLine("<H2 style='text-align:center;'>" + SystemParams.GetTextByKey(lang, "P_JS_FORASSET_COLON", "For Asset:") + " " + assignto + "</H2>");

            str.Append(GenerateDispatchHtml(lang, dispatchs, string.Empty, string.Empty));

            return str.ToString();
        }

        protected enum PrintType
        {
            WorkOrder = 1,
            DispatchRequest = 2,
            Attachment = 3
        }
    }
}
