<%@ WebHandler Language="C#" Class="filesvc" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Foresight.ServiceModel;
using IronIntel.Contractor;
using System.IO;
using IronIntel.Contractor.iisitebase;

public class filesvc : IHttpHandler
{
    private HttpRequest Request;
    public void ProcessRequest(HttpContext context)
    {
        Request = context.Request;
        context.Response.ContentType = "text/plain";
        string method = context.Request.Params["Method"];
        try
        {
            switch (method)
            {
                case "UploadAttachment":
                    string attID = UploadAttachment();
                    context.Response.Write(attID);
                    break;
                case "DeleteAttachment":
                    DeleteAttachment(context);
                    break;
                default:
                    DownLoadFile(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            SystemParams.WriteLog("error", method, "UploadFile failed", ex.ToString());
        }
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private string UploadAttachment()
    {
        string fileName = Request.Form["filename"];
        HttpPostedFile file = Request.Files["file"];
        if (file != null)
        {
            BinaryReader r = new BinaryReader(file.InputStream);
            var bs = r.ReadBytes((int)file.InputStream.Length);
            return AttachmentsManagement.AddAttachment(fileName, bs);
        }
        return "";
    }
    private void DownLoadFile(HttpContext context)
    {
        try
        {
            var sourcetype = context.Request["sourceType"];
            string attchid = context.Request["attchid"];

            string fileName = "";
            byte[] fileData = null;
            string sessionid = IronIntelBasePage.GetLoginSessionID(context.Request);
            if (sourcetype == "assetattachment")
            {
                string customerid = context.Request["custid"];
                if (string.IsNullOrEmpty(customerid))
                    customerid = SystemParams.CompanyID;
                var att = AttachmentsManagement.GetAttachment(sessionid, customerid, Convert.ToInt64(attchid));
                fileData = att.Item2;
                fileName = HttpUtility.UrlEncode(att.Item1, System.Text.Encoding.UTF8);
            }
            else if (sourcetype == "workorderattachment")
            {
                string customerid = context.Request["custid"];
                if (string.IsNullOrEmpty(customerid))
                    customerid = SystemParams.CompanyID;
                var client = FleetServiceClientHelper.CreateClient<Foresight.Fleet.Services.AssetHealth.WorkOrder.WorkOrderProvider>();
                var att = client.GetWorkOrderAttachmentData(SystemParams.CompanyID, long.Parse(attchid));
                fileData = att.Item2;
                fileName = HttpUtility.UrlEncode(att.Item1, System.Text.Encoding.UTF8);
            }
            else if (sourcetype == "woestimateattachment")
            {
                string customerid = context.Request["custid"];
                if (string.IsNullOrEmpty(customerid))
                    customerid = SystemParams.CompanyID;
                var client = FleetServiceClientHelper.CreateClient<Foresight.Fleet.Services.AssetHealth.WorkOrder.WorkOrderProvider>();
                var att = client.GetWorkOrderEstimateAttachmentData(SystemParams.CompanyID, attchid);
                fileData = att.Item2;
                fileName = HttpUtility.UrlEncode(att.Item1, System.Text.Encoding.UTF8);
            }
            else if (sourcetype == "ipackage")
            {
                string customerid = context.Request["custid"];
                if (string.IsNullOrEmpty(customerid))
                    customerid = SystemParams.CompanyID;//TODO
                fileData = InspectionManager.GetInspectionPackage(sessionid, customerid, attchid, out fileName);
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            }
            else
            {
                fileData = AttachmentsManagement.GetAttachFileData(attchid, out fileName);
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            }

            context.Response.ContentType = "application/download";
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            context.Response.BinaryWrite(fileData);
        }
        catch (Exception ex)
        {
            string s = ex.ToString();
        }
    }

    private void DeleteAttachment(HttpContext context)
    {
        string attachid = context.Request["attachid"];
        AttachmentsManagement.DeleteAttachment(attachid);
        context.Response.Write("");
    }
}