using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using System.IO;
using System.Text;
using System.Configuration;
using Fab2ApprovalSystem.ViewModels;
using System.Dynamic;
using System.Web.Script.Serialization;
using System.Threading;
using System.Diagnostics;

namespace Fab2ApprovalSystem.Controllers
{
    [Authorize]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    [SessionExpireFilter]
    public class MRBController : Controller
    {
        MRB_DMO mrbDMO = new MRB_DMO();
        WorkflowDMO wfDMO = new WorkflowDMO();
        CredentialsStorage credentialsStorage = new CredentialsStorage();

        //
        // GET: /MRB/
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /MRB/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /MRB/Create
        public ActionResult Create()
        {
            MRB mrb = new MRB();
            MRB_DMO mrbDMO = new MRB_DMO();
            mrb.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
            mrbDMO.InsertMRB(mrb);


            // Automatically Submit the Document as soon as an MRB is created
            try
            {
                PopulateCloseToQDB();
                mrbDMO.SubmitDocument(mrb.MRBNumber, (int)Session[GlobalVars.SESSION_USERID]);
                //if (appoverCount > 0)
                //    NotifyApprovers(mrb.MRBNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1);


                //if (Request.IsAjaxRequest())
                //{
                //    return Content("Redirect");
                //}
                //else
                //    return Content("Invalid");
            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrb.MRBNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
                throw new Exception(e.Message);

            }


            return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber });
        }

        //
        // POST: /MRB/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /MRB/Edit/5
        public ActionResult Edit(int issueID)
        {
            MRB mrb = new MRB();
            int isITARCompliant = 1;
            ViewBag.Status = "Pending";
            ViewBag.IsApprover = "false";
            ViewBag.IsCloser = "false";

            //ViewBag.IsApproved = "false";
            //ViewBag.IsClosed = "false";
            PopulateCloseToQDB();
            mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
            ViewBag.UserList = mrbDMO.GetUserList();

            if (isITARCompliant == 0) // not ITAR Compliant
            {
                return View("UnAuthorizedAccess");
            }
            else
            {
                if (mrb.ApprovalStatus == (int)GlobalVars.ApprovalOption.Approved)
                {
                    //ViewBag.IsApproved = "true";
                    ViewBag.Status = "Approved";
                }
                else if (mrb.ApprovalStatus == (int)GlobalVars.ApprovalOption.Closed)
                {
                    ViewBag.Status = "Closed";
                    //ViewBag.IsClosed = "true";
                }
                List<ApproversListViewModel> userList = MiscDMO.GetApproversListByDocument(issueID, mrb.CurrentStep, (int)GlobalVars.DocumentType.MRB);
                ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
                if (appUser != null)
                {
                    ViewBag.IsApprover = "true";
                }


            }

            // can edit
            ViewBag.Owners = MiscDMO.GetUserList();
            ViewBag.Modules = mrbDMO.GetModules();
            //ViewBag.Dispositions = mrbDMO.GetDispositions();
            ViewBag.RiskAssessments = mrbDMO.GetRiskAssessments();
            ViewBag.PartGroups = mrbDMO.GetPartGroups();
            ViewBag.DispoTypes = mrbDMO.GetDispositions(issueID).Select(d => new { d.DispositionType });

            return View(mrb);
        }

        //
        // POST: /MRB/Edit/5
        [HttpPost]
        public void Edit(MRB mrb)
        {
            try
            {
                mrbDMO.UpdateMRB(mrb);

            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrb.MRBNumber.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="lotDispo"></param>
        /// <returns></returns>
        public ActionResult ReadOnly(int issueID)
        {
            MRB mrb = new MRB();
            int isITARCompliant = 1;


            try
            {
                if (isITARCompliant == 0) // not ITAR Compliant
                {
                    return View("UnAuthorizedAccess");
                }
                else
                {
                    mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);

                    ViewBag.Owners = MiscDMO.GetUserList();
                    ViewBag.Modules = mrbDMO.GetModules();
                    //ViewBag.Dispositions = mrbDMO.GetDispositions();
                    ViewBag.RiskAssessments = mrbDMO.GetRiskAssessments();
                    ViewBag.PartGroups = mrbDMO.GetPartGroups();
                    ViewBag.DispoTypes = mrbDMO.GetDispositions(issueID).Select(d => new { d.DispositionType });
                }

                return View(mrb);
            }

            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n ReadOnly Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);

            }
        }

        //
        // GET: /MRB/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /MRB/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="searchBy"></param>
        /// <returns></returns>
        public JsonResult SearchLots(string searchText, string searchBy)
        {
            //IEnumerable<Lot> lotlist = MiscDMO.SearchLots(searchText, searchBy);
            List<String> lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList<String>();
            return Json(lotlist, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issueID"></param>
        /// <returns></returns>
        public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber)
        {
            return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request));
        }

        [HttpGet]
        public ActionResult GetTools()
        {
            return Json(mrbDMO.GetTools(), JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// Updates the lot tables
        /// </summary>
        /// <param name="request"></param>
        /// <param name="lot"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot)
        {

            //try
            //{
            //    // RJK
            //    //routine to cascade the "dispo type" to all the child lots in SPN

            //    MRB mrbInfo = mrbDMO.GetToolIssueStartEndDateData(lot.MRBNumber);

            //    if (!mrbInfo.ToolCSV.ToUpper().Equals("NA"))
            //    {
            //        bool existingLotUpdated;
            //            Lot l = new Lot();
            //            l.LotNumber = lot.LotNumber;
            //            if (lot.DispoType.ToString().Trim().Length == 1)
            //            {
            //                l.DispoType = lot.DispoType;
            //            }
            //            l.MRBNumber = lot.MRBNumber;
            //        // check if the lot was sent to SPN
            //        bool lotSentToSPN = mrbDMO.IsLotSentToSPN(l.LotNumber, l.MRBNumber);
            //        //only get the child lots if it has been sent to SPN to set the MRB Flag
            //        if (lotSentToSPN)
            //        {
            //            if (!mrbDMO.GetChildLotsFromSPNForDispoTypeUpdate(l.MRBNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate, lot.DispoType))
            //            {
            //                //warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber);
            //            }
            //        }

            //    }


            //}
            //catch(Exception e)
            //{
            //    // ignore the error 
            //    string s = e.InnerException.ToString();
            //}


            if (lot != null && ModelState.IsValid)
            {
                mrbDMO.UpdateMRBLot(lot);
            }

            return Json(new[] { lot }.ToDataSourceResult(request, ModelState));
        }


        /// <summary>
        /// Deletes record from the lot table
        /// </summary>
        /// <param name="request"></param>
        /// <param name="lot"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot)
        {
            try
            {
                if (lot != null && ModelState.IsValid)
                {
                    mrbDMO.DeleteMRBLot(lot.LotID);

                }
            }
            catch (Exception ex)
            {
                // TODO
                throw new Exception(ex.Message);
            }


            return Json(new[] { lot }.ToDataSourceResult(request, ModelState));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        public void DeleteAllMRBLots(int issueID)
        {
            // trap the error on then client side
            mrbDMO.DeleteAllMRBLot(issueID);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="lot"></param>
        /// <returns></returns>
        public JsonResult AddLot(Lot lot)
        {
            // This is to add a manually entered lot

            Lot l = lot;

            try
            {
                bool existingRowUpdated;
                mrbDMO.InsertLot(lot, false, out existingRowUpdated);
            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                throw new Exception(e.Message);
            }
            return Json(l, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="lotNumbers"></param>
        /// <param name="issueID"></param>
        public ActionResult AddLots(string lotNumbers, int mrbNumber)
        {
            // This is for adding lot(s) via search

            try
            {
                var warnings = new StringBuilder();

                if (lotNumbers.Length > 0)
                {
                    string[] tempLots = lotNumbers.Split(new char[] { '~' });
                    foreach (string lotNumber in tempLots)
                    {
                        bool existingRowUpdated;
                        Lot l = new Lot();
                        l.LotNumber = lotNumber;
                        l.MRBNumber = mrbNumber;
                        mrbDMO.InsertLot(l, true, out existingRowUpdated);
                        

                        //if (!existingRowUpdated)
                        //{
                        //    if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber))
                        //    {
                        //        warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber);
                        //    }
                        //}
                    }

                    //warnings.Append("No tool info, split lots will NOT be automatically searched and uploaded \n please make sure to include all the child lots in the MRB");
                }

                return Content(warnings.ToString());
            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRBNumber=" + mrbNumber.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n AddLots MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", DocumentType = "MRB", Comments = exceptionString });

                Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return Content(e.Message);
            }
        }

        #region ATTACHMENT
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issueID"></param>
        /// <returns></returns>
        public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber)
        {
            return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request));
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachmentID"></param>
        /// <param name="fileName"></param>
        [HttpPost]
        public void DeleteAttachment(int attachmentID)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var attachment = mrbDMO.GetMRBAttachment(attachmentID);

                    if (attachment == null) return;

                    String fileName = attachment.Path;
                    if (String.IsNullOrEmpty(fileName)) fileName = attachment.FileName;

                    mrbDMO.DeleteMRBAttachment(attachmentID);

                    if (!String.IsNullOrWhiteSpace(fileName))
                    {
                        var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", fileName);

                        FileInfo f = new FileInfo(physicalPath);

                        if (f.Exists)
                            f.Delete();
                    }
                }
            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString });
                throw new Exception(e.Message);

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int mrbNumber)
        {
            var errorList = new List<String>();

            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {

                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                    var fileName = Path.GetFileName(file.FileName);
                    string physicalFileName;
                    string physicalPath;

                    // Check to see if this filename is in use
                    var attachments = mrbDMO.GetMRBAttachments(mrbNumber);
                    if (attachments.Count() > 0)
                    {
                        if (attachments.Where(a => String.Equals(a.FileName, fileName, StringComparison.OrdinalIgnoreCase)).Count() > 0)
                        {
                            // This filename is used on this MRB
                            // So we want to delete those records so the new record replaces them
                            foreach (var a in attachments)
                            {
                                mrbDMO.DeleteMRBAttachment(a.AttachmentID);

                                physicalFileName = a.Path;
                                if (String.IsNullOrEmpty(physicalFileName)) physicalFileName = a.FileName;
                                physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", physicalFileName);

                                if (System.IO.File.Exists(physicalPath))
                                    System.IO.File.Delete(physicalPath);
                            }
                        }
                    }

                    physicalFileName = mrbNumber.ToString() + "_" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(fileName);
                    physicalPath = Path.Combine(Functions.GetAttachmentFolder() + "MRB", physicalFileName);

                    file.SaveAs(physicalPath);
                    MRBAttachment attach = new MRBAttachment()
                    {
                        MRBNumber = mrbNumber,
                        FileName = fileName,
                        Path = physicalFileName,
#if(DEBUG)
                        UserID = 114,
#endif

#if(!DEBUG)
                        UserID = (int)Session[GlobalVars.SESSION_USERID],
#endif
                    };
                    mrbDMO.InsertMRBAttachment(attach);
                }
            }

            //var model = mrbDMO.GetMRBAttachments(mrbNumber);


            return Json(new { errors = errorList });
        }


        #endregion


        public ActionResult ExcelLotOpen(IEnumerable<HttpPostedFileBase> Lotfile, int mrbNumber)
        {
            var warnings = new StringBuilder();
            var physicalPath = "";
            try
            {
                var dispos = mrbDMO.GetDispositions(mrbNumber);

                foreach (var file in Lotfile)
                {
                    //string guid = "";

                    string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

                    IEnumerable<ExcelData.ExcelLotInfo> lotNumbers;

                    try
                    {
                        physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), fName + "." + Path.GetExtension(file.FileName));
                        file.SaveAs(physicalPath);
                        ExcelData x = new ExcelData(physicalPath);
                        lotNumbers = x.ReadData();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(String.Format("Invalid file format for {0}: {1}", file.FileName, ex.Message));
                    }

                    // Get Tool, Issue Start and End Date

                    MRB mrbInfo = mrbDMO.GetToolIssueStartEndDateData(mrbNumber, null);

                    foreach (var lotInfo in lotNumbers)
                    {
                        if (lotInfo.LotDispo.Length == 1)
                        {
                            if (dispos.Count(d => d.DispositionType.Trim().ToUpper() == lotInfo.LotDispo.Trim().ToUpper()) == 0)
                            {
                                throw new Exception(String.Format("Invalid lot disposition {0} for lot no {1}",
                                    lotInfo.LotDispo, lotInfo.LotNo));
                            }
                        }
                    }
                    // RJK - 12/17
                    // Only find the child Splits when a Tool or a list of Tools is provided
                    if (!mrbInfo.ToolCSV.ToUpper().Equals("NA"))
                    {
                        foreach (var lotInfo in lotNumbers)
                        {
                            bool existingLotUpdated;
                            Lot l = new Lot();
                            l.LotNumber = lotInfo.LotNo;
                            if (lotInfo.LotDispo.Length == 1)
                            {
                                l.DispoType = lotInfo.LotDispo[0];
                            }
                            l.MRBNumber = mrbNumber;
                            mrbDMO.InsertLot(l, true, out existingLotUpdated);
                            // cannot do the check below , because what if the parent lot had splits after the prior lot split analysis
                            //if (!existingLotUpdated) 
                            //{
                            if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate))
                                {
                                    warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n Uploaded without Lot Genealogy tracing", l.LotNumber);
                                }
                            //}
                        }

                        // Not required - Will be using each lot's Insert Date time stamp, 
                        // as lot could be added using search functionality
                        // mrbDMO.UpdateLastLotSplitAnalysisTime(mrbNumber);


                    }
                    else
                    {
                        // RJK - 12/17
                        // Only find the child Splits when a Tool or a list of Tools is provided
                        foreach (var lotInfo in lotNumbers)
                        {
                            bool existingLotUpdated;
                            Lot l = new Lot();
                            l.LotNumber = lotInfo.LotNo;
                            if (lotInfo.LotDispo.Length == 1)
                            {
                                l.DispoType = lotInfo.LotDispo[0];
                            }
                            l.MRBNumber = mrbNumber;
                            // do not insert any new lots when importing from excel
                            mrbDMO.InsertLot(l, true, out existingLotUpdated);
                            //mrbDMO.UpdateLotDispoType(mrbNumber, l.LotNumber, l.DispoType);


                            //if (!existingLotUpdated)
                            //{
                            //    if (!mrbDMO.InsertLotSplitsAffectedByIncident(mrbNumber, l.LotNumber, mrbInfo.ToolCSV, mrbInfo.IssueStartDate, mrbInfo.IssueEndDate))
                            //    {
                            //        warnings.AppendFormat("Lot number {0} is not affected by these tools and issue start/end time.\n", l.LotNumber);
                            //    }
                            //}
                        }
                    }

                    FileInfo f = new FileInfo(physicalPath);
                    if (f.Exists)
                        f.Delete();

                }

                return Content(warnings.ToString());
            }
            catch (Exception e)
            {
                string detailedException = "";
                try
                {
                    detailedException = e.InnerException.ToString();
                }
                catch
                {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrbNumber.ToString() + "  " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n MRB Excel\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
                


                FileInfo f = new FileInfo(physicalPath);
                if (f.Exists)
                    f.Delete();

                Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return Content(e.Message);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Lotfile"></param>
        /// <returns></returns>
        public ActionResult ImportAddQDBFlag(IEnumerable<HttpPostedFileBase> AddQDBFlag, string operation)
        {
            //string path = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch());
            var physicalPath = "";
            try
            {
                IEnumerable<string> lotDataList = null;

                foreach (var file in AddQDBFlag)
                {
                    var guid = Guid.NewGuid().ToString();

                    //string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

                    //physicalPath = Path.Combine(@"C:\Websites\FabApprovalTempPipeLine", guid + "." + Path.GetExtension(file.FileName));
                    physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), guid + "." + Path.GetExtension(file.FileName));
                    file.SaveAs(physicalPath);
                    ExcelData x = new ExcelData(physicalPath);
                    lotDataList = x.ReadQDBFlagData();

                    foreach (string lotData in lotDataList)
                    {
                        mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation);
                    }

                    FileInfo f = new FileInfo(physicalPath);
                    if (f.Exists)
                        f.Delete();


                    if (SendQDBFlagToSPN(guid))
                        mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true);
                    else
                    {
                        mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false);
                        return Content("Problems while uploading to SPN");
                    }



                }

                return Content("");
            }
            catch
            {
                FileInfo f = new FileInfo(physicalPath);
                if (f.Exists)
                    f.Delete();

                return Content("Incorrect File Format/Data");
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="AddQDBFlag"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        public ActionResult ImportRemoveQDBFlag(IEnumerable<HttpPostedFileBase> RemoveQDBFlag, string operation)
        {
            var physicalPath = "";
            try
            {
                IEnumerable<string> lotDataList = null;

                foreach (var file in RemoveQDBFlag)
                {
                    var guid = Guid.NewGuid().ToString();

                    //string fName = User.Identity.Name + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

                    //physicalPath = Path.Combine(@"C:\Websites\FabApprovalTempPipeLine", guid + "." + Path.GetExtension(file.FileName));
                    physicalPath = Path.Combine(ConfigurationManager.AppSettings["LotTempPipeLine"].ToString(), guid + "." + Path.GetExtension(file.FileName));
                    file.SaveAs(physicalPath);
                    ExcelData x = new ExcelData(physicalPath);
                    lotDataList = x.ReadQDBFlagData();

                    foreach (string lotData in lotDataList)
                    {
                        mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation);
                    }

                    FileInfo f = new FileInfo(physicalPath);
                    if (f.Exists)
                        f.Delete();


                    //Send the data to SPN
                    if (SendQDBFlagToSPN(guid))
                        mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true);
                    else
                    {
                        mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false);
                        return Content("Problems while uploading to SPN");
                    }

                }

                return Content("");
            }
            catch
            {
                FileInfo f = new FileInfo(physicalPath);
                if (f.Exists)
                    f.Delete();

                return Content("Incorrect File Format/Data");
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="mrbNumber"></param>
        /// <returns></returns>

        public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber)
        {
            return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult UpdateContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model)
        //{
        //    if (model != null && ModelState.IsValid)
        //    {
        //        mrbDMO.UpdateContainmentAction(model);
        //    }


        //    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="request"></param>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult InsertContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model)
        //{

        //    if (model != null && ModelState.IsValid)
        //    {
        //        mrbDMO.InsertContainmentAction(model);
        //    }


        //    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        //}



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateContainmentAction(ContainmentActionObj model)
        {
            if (model != null && ModelState.IsValid)
            {
                mrbDMO.UpdateContainmentAction(model);
            }

            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertContainmentAction(ContainmentActionObj model)
        {

            if (model != null && ModelState.IsValid)
            {
                mrbDMO.InsertContainmentAction(model);
            }


            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model)
        {
            if (model != null && ModelState.IsValid)
            {
                mrbDMO.DeleteContainmentAction(model);
            }


            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }



        #region
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="mrbNumber"></param>
        /// <returns></returns>
        public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber)
        {
            return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request));
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult UpdateDisposition([DataSourceRequest] DataSourceRequest request, Disposition model)
        //{
        //    if (model != null && ModelState.IsValid)
        //    {
        //        mrbDMO.UpdateDisposition(model);
        //    }


        //    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        //}


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateDisposition(Disposition model)
        {
            if (model != null && ModelState.IsValid)
            {
                mrbDMO.UpdateDisposition(model);
            }

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult InsertDisposition([DataSourceRequest] DataSourceRequest request, Disposition model)
        //{

        //    if (model != null && ModelState.IsValid)
        //    {
        //        mrbDMO.InsertDisposition(model);
        //    }


        //    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        //}



        [AcceptVerbs(HttpVerbs.Post)]
        public void InsertDisposition( Disposition model)
        {

            if (model != null && ModelState.IsValid)
            {
                mrbDMO.InsertDisposition(model);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult DeleteDisposition([DataSourceRequest] DataSourceRequest request, Disposition model)
        //{
        //    if (model != null && ModelState.IsValid)
        //    {
        //        mrbDMO.DeleteDisposition(model);
        //    }


        //    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        //}

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteDisposition(Disposition model)
        {
            if (model != null && ModelState.IsValid)
            {
                mrbDMO.DeleteDisposition(model);
            }


            return Json(model, JsonRequestBehavior.AllowGet);
        }

        #endregion


        public void PopulateCloseToQDB()
        {
            List<CloseToQDBOptionViewModel> options = new List<CloseToQDBOptionViewModel>();
            options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" });
            options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" });
            //options.Add(new CloseToQDBOptionViewModel{CloseToQDBOption= "No"});
            //options.Add(new CloseToQDBOptionViewModel {CloseToQDBOption = "Yes" });

            ViewData["CloseToQDBOptions"] = options;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="peRequired"></param>
        //public ActionResult SubmitDocument(int mrbNumber)
        //{
        //    try
        //    {
        //        int appoverCount = mrbDMO.SubmitDocument(mrbNumber, (int)Session[GlobalVars.SESSION_USERID]);
        //        if (appoverCount > 0)
        //            NotifyApprovers(mrbNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1);



        //        if (Request.IsAjaxRequest())
        //        {
        //            return Content("Redirect");
        //        }
        //        else
        //            return Content("Invalid");
        //    }
        //    catch (Exception e)
        //    {
        //        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrbNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //        Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
        //        EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
        //        throw new Exception(e.Message);

        //    }
        //}


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="currentStep"></param>
        public void NotifyApprovers(int mrbNumber, byte currentStep)
        {
            string emailSentList = "";

            List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList();

            string emailTemplate = "MRBAssigned.txt";
            string userEmail = string.Empty;
            string subject = "MRB Assignment";
            string senderName = "MRB";

            foreach (string email in emailIst)
            {
                subject = "MRB Assignment";
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[3];
                emailparams[0] = mrbNumber.ToString();
                emailparams[1] = mrbNumber.ToString();
                emailparams[2] = GlobalVars.hostURL;
                userEmail = email;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                emailSentList += email + ",";
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
            }
            catch { }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MRBNumber"></param>
        public void Approve(int issueID, byte currentStep, string comments)
        {
            int isITARCompliant = 1;
            MRB mrb = new MRB();
            mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
            try
            {
                bool lastStep = false;

                bool lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber);

                while (lastApprover && !lastStep)
                {
                    currentStep++;
                    lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber);
                    NotifyApprovers(issueID, currentStep);
                }
            }
            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString });
                throw new Exception(e.Message);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="mrb"></param>
        public void CloseDocument(int mrb)
        {
            mrbDMO.CloseDocument(mrb);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="mrb"></param>
        /// <param name="dispoType"></param>
        public void SetDispositionTypeForAllLots(int mrb, string dispoType)
        {
            mrbDMO.SetDispositionTypeForAllLots(mrb, dispoType);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mrbNumber"></param>
        public JsonResult GetLotWaferDieCount(int mrbNumber)
        {



            int lotCount = 0;
            int waferCount = 0;
            int dieCount = 0;
            mrbDMO.GetLotWaferDieCount(mrbNumber, out lotCount, out waferCount, out dieCount);


            //dynamic data = new ExpandoObject();
            //data.LotCount = lotCount;
            //data.WaferCount = waferCount;
            //data.DieCount = dieCount;

            //string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);


            //return Json(json, JsonRequestBehavior.AllowGet);
            return Json(lotCount.ToString() + "~" + waferCount.ToString() + "~" + dieCount, JsonRequestBehavior.AllowGet);

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ActionResult SendMRBHoldFlagToSPN(int mrbNumber)
        {
            MRB mrbInfo;
            try
            {
                mrbInfo = mrbDMO.GetToolIssueStartEndDateData(mrbNumber);
            }
            catch
            {
                // if  tools or issue start/end date is not provided, set them to null
                mrbInfo = new MRB { ToolCSV = "", IssueStartDate = null, IssueEndDate = null };
            }

            if (!mrbInfo.ToolCSV.ToUpper().Equals("NA"))
            {
               
                Lot l = new Lot();
                
                var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber);
                foreach (Lot lot in mrbLotInfo)
                {
                    //routine to cascade the "dispo type" to all the child lots in SPN (Lot that are not present in FAb App Sys,)
                    mrbDMO.ChildLotsUpdateInSPNWithNewDispoType(lot, mrbInfo);
                                                                       
                }

            }
            
            // SEND DATA to SPN

            StringBuilder output = new StringBuilder();
            try
            {
                IEnumerable<string> data = mrbDMO.GetMRBHoldLots(mrbNumber);
                foreach (string tempData in data)
                {
                    //output = new StringBuilder();
                    if (tempData != null) 
                        output.Append(tempData.Trim() + Environment.NewLine);

                }


                try
                {
                    if (output.Length > 0)
                    {
                        DateTime dt = DateTime.Now;
                        string newsourceFileName = mrbNumber.ToString() + "_S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb";
                        string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00");

                        //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName;
                        string outputFile = ConfigurationManager.AppSettings["SPNMRBHoldFlagDirectory"].ToString() + newsourceFileName;


                        System.IO.File.WriteAllText(outputFile, output.ToString());

#if (DEBUG)
                        Thread.Sleep(1000);
#endif
                        try
                        {
                            //#if (!DEBUG)
                            //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName);
                            //spfSPN.FTPToSPN();

                            if (BatchFTP(outputFile, newDestFileName))
                            {
                                //TODO
                                mrbDMO.LogHoldFlagSentToSPNHistory(mrbNumber);
                            }

                            //#endif
                        }
                        catch (Exception e)
                        {
                            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): SendMRBHoldFlagToSPN(mrbNumber) - FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                            EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                            return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet);
                            //return false;
                        }

                    }

                    //return true;
                }
                catch (Exception e)
                {
                    string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                    Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                    return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); ;
                }

                return Json(new { Error = false, Message = "Success" }, JsonRequestBehavior.AllowGet);




            }

            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); 
            }




        }



        /// <summary>
        /// RETIRED
        /// </summary>
        /// <param name="mrbNumber"></param>
        //        public ActionResult SendSPN_MRB_HoldFlag(int mrbNumber)
        //        {
        //            StringBuilder output;
        //            try
        //            {
        //                IEnumerable<string> data = mrbDMO.GetMRB_QDB_HoldFlags(mrbNumber);
        //                foreach (string tempData in data)
        //                {
        //                    output = new StringBuilder();
        //                    output.Append(tempData.Trim() + "\n");


        //                    try
        //                    {
        //                        if (output.Length > 0)
        //                        {
        //                            DateTime dt = DateTime.Now;
        //                            string newsourceFileName = "S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb";
        //                            string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb";

        //                            string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName;

        //                            System.IO.File.WriteAllText(outputFile, output.ToString());


        //#if (DEBUG)
        //                            Thread.Sleep(1000);
        //#endif
        //                            try
        //                            {
        //#if (!DEBUG)
        //                            FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName);
        //                            spfSPN.FTPToSPN();
        //#endif
        //                            }
        //                            catch(Exception e)
        //                            {
        //                                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //                                EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });                                
        //                            }

        //                        }

        //                    }
        //                    catch (Exception e)
        //                    {
        //                        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //                        Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
        //                        EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
        //                        return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet);
        //                    }

        //                }

        //                if (data.Count() > 0)
        //                {
        //                    try
        //                    {
        //                        // Insert the new records
        //#if (!DEBUG)
        //                        mrbDMO.InsertSPN_MRB_HoldFlagLots(mrbNumber);
        //#endif
        //                        return Json(new { Error = false, Message = "" }, JsonRequestBehavior.AllowGet);

        //                    }

        //                    catch (Exception e)
        //                    {
        //                        string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(InsertSPN_MRB_HoldFlagLots) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //                        Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
        //                        EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
        //                        return Json(new { Result = true, Message = e.Message }, JsonRequestBehavior.AllowGet);
        //                    }
        //                }
        //                else
        //                {
        //                    return Json(new { Error = true, Message = "There are no new Lot Numbers that needs to be sent to SPN for an MRB Hold" }, JsonRequestBehavior.AllowGet);
        //                }

        //            }

        //            catch (Exception e)
        //            {
        //                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SPN Hold Flag(GetSPN_MRB_HoldFlagLots) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
        //                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
        //                EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
        //                return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet);
        //            }




        //        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public bool SendQDBFlagToSPN(string guid)
        {
            StringBuilder output = new StringBuilder();
            try
            {
                IEnumerable<string> data = mrbDMO.GetMRB_QDB_HoldFlags(guid);
                foreach (string tempData in data)
                {
                    //output = new StringBuilder();
                    output.Append(tempData.Trim() + Environment.NewLine);

                }


                try
                {
                    if (output.Length > 0)
                    {
                        DateTime dt = DateTime.Now;
                        string newsourceFileName = "S" + dt.Day.ToString("00") + dt.Month.ToString("00") + dt.Year.ToString("00") + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb";
                        string newDestFileName = "S" + dt.Hour.ToString("00") + dt.Minute.ToString("00") + dt.Second.ToString("00") + ".mrb";

                        //string outputFile = @"C:\Websites\SPNLotHoldFlag\" + newsourceFileName;
                        string outputFile = ConfigurationManager.AppSettings["HoldFlagDirectory"].ToString() + newsourceFileName;


                        System.IO.File.WriteAllText(outputFile, output.ToString());

#if (DEBUG)
                        Thread.Sleep(1000);
#endif
                        try
                        {
                            //#if (!DEBUG)
                            //FTPWrapper spfSPN = new FTPWrapper(outputFile, newDestFileName);
                            //spfSPN.FTPToSPN();

                            if (BatchFTP(outputFile, newDestFileName))
                            {
                                mrbDMO.UpdateMRB_QDB_HoldFlag(guid, true);
                            }
                            else
                            {
                                mrbDMO.UpdateMRB_QDB_HoldFlag(guid, false);
                            }

                            //#endif
                        }
                        catch (Exception e)
                        {
                            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " FTPToSPN(): FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                            EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                            return false;
                        }

                    }

                    return true;
                }
                catch (Exception e)
                {
                    string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                    Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                    return false;
                }






            }

            catch (Exception e)
            {
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + guid.ToString() + " SPN Hold Flag(SendToSPN) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
                return false;
            }




        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <returns></returns>
        public bool BatchFTP(string sourceFile, string destFile)
        {
            FileInfo sourcefile = new FileInfo(sourceFile);
            

            //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn");

            try
            {
                //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information);

                //System.Security.SecureString ss = new System.Security.SecureString();
                //foreach (char c in credentialsStorage.Password)
                //    ss.AppendChar(c);

                ProcessStartInfo psiFab1 = new ProcessStartInfo();
                Process procFab1 = new Process();
                StringBuilder sb = new StringBuilder();

                if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
                {
                    psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch_Test());
                }
                else
                {
                    psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch());
                }

                psiFab1.Arguments = sourcefile.FullName + " " + destFile;

                psiFab1.RedirectStandardOutput = true;
                psiFab1.UseShellExecute = false;
                psiFab1.WorkingDirectory = Server.MapPath("/FTPBatch/");
                //credentialsStorage = MiscDMO.GetCredentialsInfo("TEMSA01EC", "LocalAdmin");
                //psiFab1.UserName = credentialsStorage.UserName;
                //psiFab1.Password = ss;

                procFab1.StartInfo = psiFab1;
                procFab1.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); ;
                procFab1.Start();
                procFab1.BeginOutputReadLine();
                procFab1.WaitForExit(4000);

                string ftpLogDirectory = ConfigurationManager.AppSettings["SPNMRBHoldFlagFTPLogDirectory"].ToString();
                System.IO.File.WriteAllText(Path.Combine(ftpLogDirectory, sourcefile.Name + ".txt"), sb.ToString());


                //procFab1.StartInfo = psiFab1;
                //procFab1.Start();



                //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information);

                return true;
            }
            catch (Exception e)
            {

                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return false;
            }


        }


        public bool BatchFTP_Old(string sourceFile, string destFile)
        {
            FileInfo sourcefile = new FileInfo(sourceFile);
            //FileInfo sourcefile = new FileInfo(@"C:\Websites\ECNViewerAckResultToSPN\S15122017102017.ecn");

            try
            {
                //Functions.WriteEvent("HR Emp", "SPNData - Start Send(): FTPing " + sourceFile + " to SPN server.", System.Diagnostics.EventLogEntryType.Information);

                ProcessStartInfo psiFab1 = new ProcessStartInfo();
                //psiFab1.FileName = @Functions.FTPSPNBatch();
                if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
                {
                    psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch_Test());
                }
                else
                {
                    psiFab1.FileName = Server.MapPath("/FTPBatch/" + @Functions.FTPSPNBatch());
                }

                psiFab1.Arguments = sourcefile.FullName + " " + destFile;

                Process procFab1 = new Process();
                procFab1.StartInfo = psiFab1;
                procFab1.Start();
                //Functions.WriteEvent("HR Emp", "SPNData - Finish FTPing to SPN server.", System.Diagnostics.EventLogEntryType.Information);

                return true;
            }
            catch (Exception e)
            {

                Functions.WriteEvent(@User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return false;
            }


        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachmentID"></param>
        /// <returns></returns>
        public FileResult DownloadFile(string attachmentID)
        {
            //fileName = "ECNForm_71132.pdf";           

            var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID));

            if (attachment == null) throw new Exception("Invalid attachment ID");

            String fileName = attachment.Path;
            if (String.IsNullOrEmpty(fileName)) fileName = attachment.FileName;

            var sDocument = Path.Combine(Functions.GetAttachmentFolder() + "MRB", fileName);
            var FDir_AppData = Functions.GetAttachmentFolder();
            if (!sDocument.StartsWith(FDir_AppData))
            {
                // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
                // and block requests outside like "../web.config"
                throw new HttpException(403, "Forbidden");
            }

            if (!System.IO.File.Exists(sDocument))
            {
                return null;
                //throw new Exception("File not found");
            }

            return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, attachment.FileName);
        }

        private string FormCSV(params object[] args)
        {
            bool first = true;
            var sb = new StringBuilder();
            foreach (object arg in args)
            {
                if (!first)
                    sb.Append(",");
                String s = Convert.ToString(arg);
                s = s.Replace('\r', ' ').Replace('\n', ' ').Replace('"', ' ');
                if (s.Contains(','))
                {
                    sb.Append("\"");
                    sb.Append(s);
                    sb.Append("\"");
                }
                else
                {
                    sb.Append(s);
                }
                first = false;
            }
            return sb.ToString();
        }
        public FileResult ExportMRBHoldFlagReport(int mrbNumber)
        {
            var sb = new StringBuilder();
            sb.AppendLine("LotNo,PartNo ,CurrentLocation,CurrentOperation,StartQty,CurrentQty,LotStatus,OperStatus,Successful,Comment,PriorMRB_DispoType,PriorMRBHoldLocation,PriorMRBHoldOperation,CurrentMRB_DispoType,CurrentMRBHoldLocation,CurrentMRBHoldOperation,TransactionDatetime");
            foreach (var report in mrbDMO.GetMRBHoldFlagReport(mrbNumber))
            {
                sb.AppendLine(FormCSV(
                   report.LotNo,
                   report.PartNo,
                   report.CurrentLocation,
                   report.CurrentOperation,
                   report.StartQty,
                   report.CurrentQty,
                   report.LotStatus,
                   report.OperStatus,
                   report.Successful,
                   report.Comment,
                   report.PriorMRB_DispoType,
                   report.PriorMRBHoldLocation,
                   report.PriorMRBHoldOperation,
                   report.CurrentMRB_DispoType,
                   report.CurrentMRBHoldLocation,
                   report.CurrentMRBHoldOperation,
                   report.TransactionDateTime

                ));
            }
            var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString());
            return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv");
        }

        public FileResult PreviewMRBHoldFlagTobeSentToSPN(int mrbNumber)
        {
             
            var sb = new StringBuilder();
            sb.AppendLine("LotNumber,MRBNumber,DispoType,MRB Flag,Modified,Sent To SPN,Last Sent to SPN");
            foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber))
            {
                sb.AppendLine(FormCSV(
                    lot.LotNumber,
                    lot.MRBNumber,
                    lot.DispoType,
                    lot.AddRemoveChangeMRBFlag,
                    lot.IsDirty,
                    lot.SentToSPN,
                    lot.MRBLotLastSentToSPNDatetime
                ));
            }
            var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString());
            return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv");
        
        }

        public FileResult ExportLots(int mrbNumber)
        {
            var sb = new StringBuilder();
            sb.AppendLine("LotNumber,DieLotNumber,WipPartNo,DispoType,WaferCount,DiePartNo,DieCount,SourceLot,TotalCost,ProductFamily,Gen,HexSize,Channel,Voltage,Location,Status,QualityCode");
            foreach (var lot in mrbDMO.GetMRBLots(mrbNumber))
            {
                sb.AppendLine(FormCSV(
                    lot.LotNumber,
                    lot.DieLotNumber,
                    lot.WipPartNo,
                    lot.DispoType,
                    lot.WaferCount,
                    lot.DiePartNo,
                    lot.DieCount,
                    lot.SourceLot,
                    lot.TotalCost,
                    lot.ProductFamily,
                    lot.Gen,
                    lot.Hexsize,
                    lot.Channel,
                    lot.Voltage,
                    lot.Location,
                    lot.Status,
                    lot.QualityCode
                ));
            }
            var b = System.Text.ASCIIEncoding.ASCII.GetBytes(sb.ToString());
            return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv");
        }


    }
}