using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BPMService.Models;
using Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using ServiceStack.Text;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.Master.PrintSupplement;
using WK_KLI_LAPS_Service.Models;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.Controllers.Master.LotBatch
{

    [Route("api/[controller]")]
    [ApiController]
    public class LotBatchApiController : ControllerBase
    {
        CommonRepository oCommonRepository = new CommonRepository();

        private ILotBatchService _LotBatchService;
        MasterRepository oMasterRepository = new MasterRepository();
        private IPrintSupplementService _PrintSupplementservices;
        public static bool isWindowsWK = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        public static string localpathwindows = System.AppDomain.CurrentDomain.BaseDirectory;
        public static string XMLFilepathwindows = Path.Combine(localpathwindows, "Temp", "OutlineConfig");
        public static string localpathlinux = Startup.Configuration.GetValue<string>("AppSettings:editortoolspathlinux");
        public static string XMLFilepathlinux = Path.Combine(localpathlinux, "Temp", "OutlineConfig");
        public static string exportwordfilepathlinux = Startup.Configuration.GetValue<string>("AppSettings:exportwordfilepathlinux");
        public LotBatchApiController(ILotBatchService LotBatchService, IPrintSupplementService PrintSupplementServices)
        {
            _LotBatchService = LotBatchService;
            _PrintSupplementservices = PrintSupplementServices;
        }

        [Authorize]
        [HttpGet]
        //Code to retrieve all data
        public IActionResult GetAll()
        {
            var _list = _LotBatchService.GetAll();
            return Ok(_list);
        }

        [Authorize]
        [HttpGet("GetActiveLot")]
        //Code to retrieve active data
        public IActionResult GetActiveLot()
        {
            var _list = _LotBatchService.GetActiveLot();
            return Ok(_list);
        }

        //Code to add new record
        [Authorize]
        [HttpPost("Add")]
        public IActionResult Add([FromBody] List<lotBatchModel> olotmaster)
        {
            try
            {
                string inputstr = JsonConvert.SerializeObject(olotmaster);
                var retval = _LotBatchService.Add(inputstr, "insert");
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        //Code to update specific record
        [Authorize]
        [HttpPut("Update")]
        public IActionResult Update([FromBody]lotBatchModel olotmaster)
        {
            int retval = 0;
            try
            {
                retval = _LotBatchService.Edit(olotmaster);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }

        //Code to activate or deactivate specific record
        [Authorize]
        [HttpPost("activeordeactive")]
        public IActionResult Delete([FromBody]lotBatchModel olotmaster)
        {
            int retval = 0;
            try
            {
                retval = _LotBatchService.Delete(olotmaster);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        //Code to add new record
        [Authorize]
        [HttpPost("PostBatch")]
        public IActionResult PostBatch([FromBody] lotBatchModel olotmaster)
        {
            try
            {
                if (string.IsNullOrEmpty(olotmaster.batchname))
                    throw new Exception("Value should not be empty");
                string inputstr = JsonConvert.SerializeObject(olotmaster);

                // bool _exists = oMasterRepository.CheckExists("lotbatch", inputstr,false);
                // int result = 0;
                //  if (_exists == false)
                //  {
                var result = _LotBatchService.PostBatch(olotmaster, "insert");
                if (result != null)
                {
                    var tras = JsonConvert.DeserializeObject<object>(result.ToString());
                    // JArray Checkinapplist = JArray.Parse(i_appType.ToString());
                    var batchid = new { transactionid = tras.ToString() };
                    var transobject = new
                    {
                        printsupplementid = olotmaster.printsupplementid,
                        batchid = tras.ToString()
                    };
                    string jsonstr = JsonConvert.SerializeObject(transobject);
                    var retval = _PrintSupplementservices.Edit(jsonstr, "updatebatchid");

                    // var url = "https://172.16.1.78:49990/orchestration/api/PubflowApi/Online/Update_Online_Copy_Editing";
                    var url = Startup.Configuration.GetValue<string>("AppSettings:kLI_Update_Manual_Copy_Editing");
                    var client = new RestClient(url);
                    var pubflowrequest = new RestRequest(Method.POST);
                    pubflowrequest.AddHeader("Content-Type", "application/json");
                    pubflowrequest.RequestFormat = DataFormat.Json;
                    Console.WriteLine("LAPS2 App Watcher: url" + url);
                    Console.WriteLine("LAPS2 App Watcher: UserID" + olotmaster.createdby);
                    // Console.WriteLine("LAPS2 App Watcher: comment" + olotmaster.comment);
                    pubflowrequest.AddParameter("application/json", "" +
                                                                "{ " +
                                                                "\"PublicationType\":\"" + "Manual" + "\"," +
                                                                "\"PublicationID\":\"" + olotmaster.publicationid + "\"," +
                                                                "\"SupplementNumber\":\"" + olotmaster.supplementnumber + "\"," +
                                                                "\"Notes\":\"" + "test" + "\"" +
                                                                "}", ParameterType.RequestBody);
                    IRestResponse responseResult = client.Execute(pubflowrequest);
                }
                return Ok(result);
                //   }
                //   return Ok(result);


            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("GetByIssupplement/{issupplement}")]
        public IActionResult GetByIssupplement(Int32 issupplement)
        {
            try
            {
                var list = _LotBatchService.GetByIssupplement(issupplement);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("GetChapterDetailsbyJobid/{jobid}")]
        public IActionResult GetChapterDetailsbyJobid(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.GetChapterDetailsbyJobid(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpGet("Getjobstatecount/{jobid}")]
        public IActionResult Getjobstatecount(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.Getjobstatecount(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("Getsupplement/{jobid}")]
        public IActionResult Getsupplement(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.GetSupplement(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("GetisProcessing/{jobid}")]
        public IActionResult GetisProcessing(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.GetisProcessing(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpGet("GetisProcessing2/{jobid}")]
        public IActionResult GetisProcessing2(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.GetisProcessing2(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpGet("Finalsubmission/{jobid}")]
        public IActionResult Finalsubmission(Int32 jobid)
        {
            try
            {
                var list = _LotBatchService.finalsubmission(jobid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }


        [Authorize]
        [HttpGet("Getsuppview/{jobid}/{batchid}")]
        public IActionResult Getsuppview(Int64 jobid, Int64 batchid)
        {
            try
            {
                var list = _LotBatchService.Getsuppview(jobid, batchid);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("Savesupplement")]
        public object Savesupplement(List<chapdata> postdata)
        {
            string SelectQueryForLot = "";
            string logRootPath = @"/efs/connectlinux.txt";
            // var logRootPath = HttpContext.Current.Server.MapPath("~/App_Data/supplementlog.txt");
            var logSuppPath = Path.Combine(Path.GetDirectoryName(logRootPath), Path.GetFileNameWithoutExtension(logRootPath) + "_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + Path.GetExtension(logRootPath));
            int createdBy = postdata[0].userid;
            if (!System.IO.File.Exists(logSuppPath))
            {
                var myFile = System.IO.File.Create(logSuppPath);
                myFile.Close();
            }
            using (StreamWriter writer1 = new StreamWriter(logSuppPath, true))
            {
                int getJobId = 0;
                // var batch = postdata["objbat"].ToObject<lotBatchModel>();
                var chap = postdata;
                List<lottriger> lotids = new List<lottriger>();
                // var contact = db.Lot_Batchs.Where(u => u.batchname.ToLower().Trim() == batch.batchname.ToLower().Trim() && u.jobid == batch.jobid).Select(u => u.batchname).ToList();

                try
                {
                    //if (contact.Count > 0)
                    //{
                    //    return Json(new
                    //    {
                    //        Success = true, //error
                    //        Message = "Warning" //return exception
                    //    });
                    //}
                    //  else
                    // {
                    Int32 id = 0;
                    //Lot_batch_details batchdetails = new Lot_batch_details();
                    //Lot_Batch lotbatch = new Lot_Batch();
                    //lotbatch.batchname = batch.batchname;
                    //lotbatch.jobid = batch.jobid;
                    //lotbatch.batchstatus = "R";
                    //lotbatch.volume = "1";
                    //lotbatch.issue = "1";
                    //lotbatch.active = 1;
                    //lotbatch.createdby = Convert.ToInt32(HttpContext.Current.Session["UserID"] as string);
                    //lotbatch.createdon = DateTime.Now;
                    //lotbatch.issupplement = 1;
                    //writer1.WriteLine("BatchName :" + lotbatch.batchname + "    " + "JobID :" + lotbatch.jobid);
                    //writer1.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);

                    getJobId = postdata[0].jobid;
                    //if (batch.mergedproof == 1)
                    //{
                    //    lotbatch.mergedproof = 1;
                    //}
                    //else
                    //{
                    //    lotbatch.mergedproof = 0;
                    //}

                    //db.Lot_Batchs.Add(lotbatch);
                    //int success = db.SaveChanges();


                    id = Convert.ToInt32(postdata[0].batchid);
                    List<long> listLotids = new List<long>();
                    foreach (var item in chap)
                    {
                        var cdata = item;
                        // cdata.isprocessed = cdata.isprocessed != true ? false : cdata.isprocessed;

                        if (cdata.chaptertype.ToLower() != "chapter")
                        {
                            listLotids.Add(cdata.lotid);
                            writer1.WriteLine("ChapterType :" + cdata.chaptertype.ToLower() + " " + "LotID :" + cdata.lotid);
                        }
                        else
                        {
                            writer1.WriteLine("ChapterType :" + cdata.chaptertype.ToLower() + " " + "LotID :" + cdata.lotid);
                        }

                        Lot_batch_details batchdetails = new Lot_batch_details();
                        int retval = 0;
                        var chpdetails = "";
                        using (IDbConnection dbConnection = ConnectionBase.Connection)
                        {
                            dbConnection.Open();
                            DynamicParameters param = new DynamicParameters();
                            var lotdata = new
                            {
                                lotid = cdata.lotid,
                                batchid = id
                            };
                            string lotinput = JsonConvert.SerializeObject(lotdata);
                            param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                            param.Add("mode_p", dbType: DbType.String, value: "getbylotandbatchid", direction: ParameterDirection.Input);

                            chpdetails = dbConnection.Query<string>("splotbatchdetailsselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                            if (chpdetails != null)
                            {
                                //batchdetails = chpdetails;
                                batchdetails.batchid = id;
                                batchdetails.active = 1;
                                batchdetails.lotid = cdata.lotid;
                                batchdetails.istabcard = cdata.istabcard;
                                batchdetails.tabcardtitle = cdata.tabcardtitle;
                                batchdetails.isprocessed = cdata.isprocessed;
                            }
                            else
                            {
                                batchdetails.batchid = id;
                                batchdetails.active = 1;
                                batchdetails.lotid = cdata.lotid;
                                batchdetails.istabcard = cdata.istabcard;
                                batchdetails.tabcardtitle = cdata.tabcardtitle;
                                batchdetails.isprocessed = cdata.isprocessed;
                                // db.Lot_batch_detailss.Add(batchdetails);
                            }
                            // db.SaveChanges();


                            retval = oCommonRepository.ExecuteSP_ReturnInt("splotbatchdetails", batchdetails, "insert", "Add new outline");
                            klilotdefaultprodwfModel defaltProductionWf = new klilotdefaultprodwfModel();

                            defaltProductionWf.jobid = getJobId;
                            defaltProductionWf.lotid = cdata.lotid;
                            defaltProductionWf.productionworkflowid = cdata.productionworkflowid;
                            defaltProductionWf.lotbatchdetailsid = retval;
                            defaltProductionWf.createdby = createdBy;

                            retval = oCommonRepository.ExecuteSP_ReturnInt("spklilotdefaultprodwf", defaltProductionWf, "insert", "Adding new KLI_DefaultProductionWorkflow");
                        }

                        // var jobflowid1 = db.Job_Workflow_Masters.Where(x => x.jobid == postdata[0].jobid && x.stage_type == 2).OrderBy(x => x.jobworkflowid).Take(1).Select(x => x.jobworkflowid).ToList();

                        var data = new { jobid = postdata[0].jobid };

                        string input = JsonConvert.SerializeObject(data);
                        var jobflowid1 = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", input, "getbyjobidandstagetype");
                        if (jobflowid1 != null)
                        {


                            var next_ordernodata1 = JsonConvert.DeserializeObject<object>(jobflowid1.ToString());
                            JArray dt = JArray.Parse(next_ordernodata1.ToString());
                            JObject obj1_jobid = JObject.Parse(dt[0].ToString());
                            jobflowid1 = obj1_jobid["jobworkflowid"].ToString();
                        }
                        //long jobwfID = Convert.ToInt64(jobflowid1.ToString());
                        if (retval != null)
                        {
                            bool isWindowsWK = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                            if (isWindowsWK)
                            {
                                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", batchdetails.lotid.ToString()))
                                {
                                    string serverlotpath = Path.GetDirectoryName(oCommonRepository.GetServerPath(batchdetails.lotid.ToString(), "serverinfo_lot", false));
                                    var data1 = new
                                    {
                                        errormessage = (serverlotpath + " ").ToString(),
                                        createdby = 0,
                                        controller = "LotBatchApi: save supplement serverlotpath"
                                    };
                                    retval = oCommonRepository.addlog(data1, "errorlog");
                                    writer1.WriteLine("serverlotpath:" + serverlotpath);
                                    string sParentPath = Path.Combine(Path.GetDirectoryName(serverlotpath), "Parent");
                                    writer1.WriteLine("sParentPath:" + sParentPath);
                                    data1 = new
                                    {
                                        errormessage = (sParentPath + " ").ToString(),
                                        createdby = 0,
                                        controller = "LotBatchApi: save supplement sParentPath"
                                    };
                                    retval = oCommonRepository.addlog(data1, "errorlog");
                                    string servertranpath = oCommonRepository.GetServerPathbatch(batchdetails.lotid.ToString(), id, false, "serverinfo_batch");
                                    writer1.WriteLine("servertranpath:" + servertranpath);
                                    data1 = new
                                    {
                                        errormessage = (servertranpath + " ").ToString(),
                                        createdby = 0,
                                        controller = "LotBatchApi: save supplement servertranpath"
                                    };
                                    retval = oCommonRepository.addlog(data1, "errorlog");
                                    writer1.WriteLine("LotFileName:" + Path.GetFileName(servertranpath));
                                    writer1.WriteLine("----------------------" + Environment.NewLine);

                                    if (!Directory.Exists(servertranpath))
                                    { Directory.CreateDirectory(servertranpath); }
                                    DirectoryCopy(serverlotpath, servertranpath, true);

                                    lotids.Add(new lottriger() { lotid = cdata.lotid, Transid = batchdetails.lotid, userid = postdata[0].userid });
                                }
                            }
                            else
                            {
                                string serverlotpath = Path.GetDirectoryName(oCommonRepository.GetServerPath(batchdetails.lotid.ToString(), "serverinfo_lot", false));
                                var data1 = new
                                {
                                    errormessage = (serverlotpath + " ").ToString(),
                                    createdby = 0,
                                    controller = "LotBatchApi: save supplement serverlotpath"
                                };
                                retval = oCommonRepository.addlog(data1, "errorlog");
                                writer1.WriteLine("serverlotpath:" + serverlotpath);
                                string sParentPath = Path.Combine(Path.GetDirectoryName(serverlotpath), "Parent");
                                writer1.WriteLine("sParentPath:" + sParentPath);
                                data1 = new
                                {
                                    errormessage = (sParentPath + " ").ToString(),
                                    createdby = 0,
                                    controller = "LotBatchApi: save supplement sParentPath"
                                };
                                retval = oCommonRepository.addlog(data1, "errorlog");
                                string servertranpath = oCommonRepository.GetServerPathbatch(batchdetails.lotid.ToString(), id, false, "serverinfo_batch");
                                writer1.WriteLine("servertranpath:" + servertranpath);
                                data1 = new
                                {
                                    errormessage = (servertranpath + " ").ToString(),
                                    createdby = 0,
                                    controller = "LotBatchApi: save supplement servertranpath"
                                };
                                retval = oCommonRepository.addlog(data1, "errorlog");
                                writer1.WriteLine("LotFileName:" + Path.GetFileName(servertranpath));
                                writer1.WriteLine("----------------------" + Environment.NewLine);

                                if (!Directory.Exists(servertranpath))
                                { Directory.CreateDirectory(servertranpath); }
                                DirectoryCopy(serverlotpath, servertranpath, true);

                                lotids.Add(new lottriger() { lotid = cdata.lotid, Transid = batchdetails.lotid, userid = postdata[0].userid });
                            }
                           
                        }

                        if (cdata.isprocessed == 1)
                        {
                            string Results = iSProcessedLot(cdata.lotid, getJobId, postdata[0].userid);
                            //Just for info
                            //writer1.WriteLine("SP-job_back_forwad:(" + transid + "," + getsequence + "," + maxSequence + ",SW," + HttpContext.Current.Session["UserID"].ToString() + ")");
                            writer1.WriteLine(Results);
                        }
                        else
                        {
                            //ChapterType is Not equal to Chapter this Below function will Execute FMBM in word Submission then it should move to MS Review on 4/17/2020
                            // var chpdetails = db.Database.SqlQuery<jsonvalue>("SELECT json_build_object('chaptertypename', CTM.chaptertype)as json FROM Lot_master LM " +
                            //     "LEFT JOIN chaptertype_master CTM ON LM.chaptertypeid = CTM.chaptertypeid WHERE LM.lotid = @lotid", new Npgsql.NpgsqlParameter { ParameterName = "@lotid", Value = batchdetails.lotid }).ToList();
                            // chaptertypedetail jsonchap = JsonConvert.DeserializeObject<chaptertypedetail>(chpdetails[0].json);

                            chaptertypedetail jsonchap = new chaptertypedetail();

                            using (IDbConnection dbConnection = ConnectionBase.Connection)
                            {
                                dbConnection.Open();
                                DynamicParameters param = new DynamicParameters();
                                // param.Add("lotid", dbType: DbType.Int64, value: Convert.ToInt64(batchdetails.lotid), direction: ParameterDirection.Input);
                                var lotdata = new
                                {
                                    lotid = Convert.ToInt64(batchdetails.lotid),
                                    batchid = id
                                };
                                string lotinput = JsonConvert.SerializeObject(lotdata);
                                param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                param.Add("mode_p", dbType: DbType.String, value: "getbylotid", direction: ParameterDirection.Input);
                                var getTransid = dbConnection.Query<string>("public.splotmasterselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                                if (getTransid != null)
                                {
                                    var i1_tranid = JsonConvert.DeserializeObject<object>(getTransid.ToString());
                                    JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                                    JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                                    jsonchap.chaptertypename = obj1_tranid["chaptertypename"].ToString();


                                    if (jsonchap.chaptertypename.ToLower() != "chapter")
                                    {
                                        // if isprocessed == false, then the following
                                        // long jobwID = Convert.ToInt64(jobflowid1[0].ToString());

                                        var data1 = new { jobid = postdata[0].jobid };
                                        string input1 = JsonConvert.SerializeObject(data1);
                                        var jobflowid2 = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", input1, "getbyjobidandstagetype");
                                        if (jobflowid2 != null)
                                        {
                                            var next_ordernodata1 = JsonConvert.DeserializeObject<object>(jobflowid2.ToString());
                                            JArray dt = JArray.Parse(next_ordernodata1.ToString());
                                            JObject obj1_jobid = JObject.Parse(dt[0].ToString());
                                            jobflowid2 = obj1_jobid["jobworkflowid"].ToString();
                                            long jobwID = Convert.ToInt64(jobflowid2.ToString());
                                            string lstatus = "R";
                                            SelectQueryForLot = "select * from lot_transaction Where jobworkflowid = " + jobwID + " and lotid = " + cdata.lotid + "  and lotstatus ='R'";
                                            writer1.WriteLine("SelectQueryForLot:" + SelectQueryForLot);
                                            string statusoffmbmmove = Fmbmmove(jobwID, cdata.lotid, lstatus, writer1, createdBy);
                                            if (statusoffmbmmove != "success")
                                            {
                                                writer1.WriteLine("Message :" + statusoffmbmmove + Environment.NewLine + "SelectQueryForLot:" + SelectQueryForLot + Environment.NewLine +
                                            "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                                                writer1.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }


                }
                catch (Exception ex)
                {
                    string filePath1 = @"/efs/connectlinux.txt";
                    using (StreamWriter writer = new StreamWriter(filePath1, true))
                    {
                        writer.WriteLine("Message :" + ex.Message + Environment.NewLine + "SelectQueryForLot:" + SelectQueryForLot + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                           "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                        writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                    }
                }
                return lotids;
            }
        }


        [Authorize]
        [HttpPost("updatesupplement")]
        public object updatesupplement(List<updatedsupp> postdata)
        {
            string logRootPath = @"/efs/connectlinux.txt";
            var logSuppPath = Path.Combine(Path.GetDirectoryName(logRootPath), Path.GetFileNameWithoutExtension(logRootPath) + "_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + Path.GetExtension(logRootPath));
            int createdBy = postdata[0].userid;
            if (!System.IO.File.Exists(logSuppPath))
            {
                var myFile = System.IO.File.Create(logSuppPath);
                myFile.Close();
            }

            string SelectQueryForLot = "";
            string results = "";
            bool isSupplementProcedflg = false;
            bool trigger = false;
            /// BLDatamanipulation db1 = new BLDatamanipulation();
            List<lottriger> lotids = new List<lottriger>();
            try
            {
                using (StreamWriter writer1 = new StreamWriter(logSuppPath, true))
                {
                    writer1.WriteLine("Update Supplement Start..." + "<br/>");
                    //List<lottriger> lotids = new List<lottriger>();
                    foreach (var item in postdata.Where(x => x.ishide == 0 && x.ischeck == 1))
                    {
                        bool FleMoveflg = false;
                        item.editisprocessed = item.editisprocessed != 1 ? 0 : item.editisprocessed;
                        item.isprocessed = item.isprocessed != 1 ? 0 : item.isprocessed;
                        Lot_batch_details batchdetails = new Lot_batch_details();
                        int retval = 0;
                        var chpdetails = "";
                        using (IDbConnection dbConnection = ConnectionBase.Connection)
                        {
                            dbConnection.Open();

                            DynamicParameters param = new DynamicParameters();

                            var lotdata = new
                            {
                                lotid = item.lotid,
                                batchid = item.batchid
                            };
                            string lotinput = JsonConvert.SerializeObject(lotdata);
                            param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                            param.Add("mode_p", dbType: DbType.String, value: "getbylotandbatchid", direction: ParameterDirection.Input);

                            chpdetails = dbConnection.Query<string>("splotbatchdetailsselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                            if (chpdetails != null)
                            {
                                // batchdetails = chpdetails;
                                batchdetails.batchid = item.batchid;
                                batchdetails.active = 1;
                                batchdetails.lotid = item.lotid;
                                batchdetails.istabcard = item.istabcard;
                                batchdetails.tabcardtitle = item.tabcardtitle;
                                if (item.editisprocessed == 1)
                                {
                                    batchdetails.isprocessed = item.editisprocessed;
                                    FleMoveflg = true;
                                }
                                else
                                {
                                    batchdetails.isprocessed = item.isprocessed;
                                }
                                writer1.WriteLine("BatchId:" + batchdetails.batchid + "  " + "Lotid:" + batchdetails.lotid + "<br/>");
                            }
                            else
                            {
                                batchdetails.batchid = item.batchid;
                                batchdetails.active = 1;
                                batchdetails.lotid = item.lotid;
                                batchdetails.istabcard = item.istabcard;
                                batchdetails.tabcardtitle = item.tabcardtitle;
                                batchdetails.isprocessed = item.isprocessed;
                                writer1.WriteLine("BatchId:" + batchdetails.batchid + "  " + "Lotid:" + batchdetails.lotid + "<br/>");
                                //  db.Lot_batch_detailss.Add(batchdetails);
                            }
                            // db.SaveChanges();
                            retval = oCommonRepository.ExecuteSP_ReturnInt("splotbatchdetails", batchdetails, "insert", "Add new outline");

                            klilotdefaultprodwfModel defaltProductionWf = new klilotdefaultprodwfModel();

                            defaltProductionWf.jobid = Convert.ToInt32(item.jobid);
                            defaltProductionWf.lotid = Convert.ToInt32(item.lotid);
                            defaltProductionWf.productionworkflowid = item.productionworkflowid;
                            defaltProductionWf.lotbatchdetailsid = retval;
                            defaltProductionWf.updatedby = createdBy;

                            retval = oCommonRepository.ExecuteSP_ReturnInt("spklilotdefaultprodwf", defaltProductionWf, "insert", "Updating KLI_DefaultProductionWorkflow");

                        }
                        if (retval != null)
                        {
                            if (!FleMoveflg)
                            {
                                bool isWindowsWK = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                                if (isWindowsWK)
                                {
                                    using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", batchdetails.lotid.ToString()))
                                    {
                                        // ServerInfo servinfo = new ServerInfo();
                                        string serverlotpath = Path.GetDirectoryName(oCommonRepository.GetServerPath(batchdetails.lotid.ToString(), "serverinfo_lot", true));
                                        writer1.WriteLine("serverlotpath:" + serverlotpath + "<br/>");
                                        string sParentPath = Path.Combine(Path.GetDirectoryName(serverlotpath), "Parent");
                                        writer1.WriteLine("sParentPath:" + sParentPath + "<br/>");
                                        string servertranpath = oCommonRepository.GetServerPathbatch(batchdetails.lotid.ToString(), Convert.ToInt32(item.batchid), false, "serverinfo_batch");
                                        writer1.WriteLine("servertranpath:" + servertranpath + "<br/>");
                                        if (!Directory.Exists(servertranpath))
                                        { Directory.CreateDirectory(servertranpath); }
                                        DirectoryCopy(serverlotpath, servertranpath, true);
                                        writer1.WriteLine("LotFileName" + Path.GetFileName(serverlotpath) + "<br/>");
                                        writer1.WriteLine(Environment.NewLine + "----------------------" + "<br/>");
                                    }
                                }
                                else
                                {
                                    string serverlotpath = Path.GetDirectoryName(oCommonRepository.GetServerPath(batchdetails.lotid.ToString(), "serverinfo_lot", true));
                                    writer1.WriteLine("serverlotpath:" + serverlotpath + "<br/>");
                                    string sParentPath = Path.Combine(Path.GetDirectoryName(serverlotpath), "Parent");
                                    writer1.WriteLine("sParentPath:" + sParentPath + "<br/>");
                                    string servertranpath = oCommonRepository.GetServerPathbatch(batchdetails.lotid.ToString(), Convert.ToInt32(item.batchid), false, "serverinfo_batch");
                                    writer1.WriteLine("servertranpath:" + servertranpath + "<br/>");
                                    if (!Directory.Exists(servertranpath))
                                    { Directory.CreateDirectory(servertranpath); }
                                    DirectoryCopy(serverlotpath, servertranpath, true);
                                    writer1.WriteLine("LotFileName" + Path.GetFileName(serverlotpath) + "<br/>");
                                    writer1.WriteLine(Environment.NewLine + "----------------------" + "<br/>");
                                }

                            }
                            lotids.Add(new lottriger() { lotid = batchdetails.lotid, Transid = batchdetails.lotid, userid = postdata[0].userid });
                        }
                        if (item.isprocessed == 1 || item.editisprocessed == 1)
                        {
                            if (!trigger)
                                isSupplementProcedflg = isSupplementProcessed(postdata[0].jobid.ToString());

                            results = iSProcessedLot(Convert.ToInt32(item.lotid.ToString()), Convert.ToInt32(item.jobid.ToString()), postdata[0].userid);
                            lotids[lotids.Count - 1].Transid = Convert.ToInt32(results.Replace("(", ",").Split(',')[1].ToString());

                            //Supplement created &Processed and adding new lot first tranid status should "R" to Trigger the Queue on 4/23/2020
                            if (isSupplementProcedflg && !trigger)
                            {
                                Npgsql.NpgsqlParameter[] sParams2 = { new Npgsql.NpgsqlParameter("@transactionid", results.Replace("(", ",").Split(',')[1].ToString()) };

                                //  var dt1 = db1.InsertQuery(db, "update lot_transaction set lotstatus = 'R' where transactionid =  @transactionid", sParams2.ToList());

                                using (IDbConnection dbConnection = ConnectionBase.Connection)
                                {
                                    dbConnection.Open();
                                    DynamicParameters param = new DynamicParameters();
                                    var lotdata = new
                                    {
                                        status = 'R',
                                        p_option = "lotstatusUpdate"
                                    };
                                    string lotinput = JsonConvert.SerializeObject(lotdata);
                                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                    dbConnection.Query<string>("public.spusrlottransactionupdate", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                                }

                                lotids[0].Transid = Convert.ToInt32(results.Replace("(", ",").Split(',')[1].ToString());
                            }
                            trigger = true;
                            writer1.WriteLine(results);
                        }
                        else
                        {
                            ////ChapterType is Not equal to Chapter this Below function will Execute FMBM in word Submission then it should move to MS Review on 4/17/2020
                            //var chpdetails = db.Database.SqlQuery<jsonvalue>("SELECT json_build_object('chaptertypename', CTM.chaptertype)as json FROM Lot_master LM" +
                            //    " LEFT JOIN chaptertype_master CTM ON LM.chaptertypeid = CTM.chaptertypeid WHERE LM.lotid = @lotid", new Npgsql.NpgsqlParameter { ParameterName = "@lotid", Value = batchdetails.lotid }).ToList();
                            //chaptertypedetail jsonchap = JsonConvert.DeserializeObject<chaptertypedetail>(chpdetails[0].json);

                            //if (jsonchap.chaptertypename.ToLower() != "chapter")
                            //{
                            //    //While Creating Supplement the jobworkflowid and lotstatus is R , Move it in server IN directly FEB 7 2019
                            //    var jobflowid1 = db.Job_Workflow_Masters.Where(x => x.jobid == item.jobid && x.stage_type == 2).OrderBy(x => x.jobworkflowid).Take(1).Select(x => x.jobworkflowid).ToList();
                            //    writer1.WriteLine("JobWorkflowID:" + Convert.ToInt64(jobflowid1[0].ToString()) + "<br/>" + "<br/>");
                            //    long jobwID = Convert.ToInt64(jobflowid1[0].ToString());
                            //    string lstatus = "R";
                            //    SelectQueryForLot = "select * from lot_transaction Where jobworkflowid = " + jobwID + " and lotid = " + batchdetails.lotid + "  and lotstatus ='R'";
                            //    writer1.WriteLine("SelectQueryForLot:" + SelectQueryForLot);
                            //    string statusoffmbmmove = Fmbmmove(jobwID, batchdetails.lotid, lstatus, writer1, createdBy);
                            //    if (statusoffmbmmove != "success")
                            //    {
                            //        writer1.WriteLine("Message :" + statusoffmbmmove + Environment.NewLine + "SelectQueryForLot:" + SelectQueryForLot + Environment.NewLine +
                            //    "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                            //        writer1.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                            //    }
                            //}

                            chaptertypedetail jsonchap = new chaptertypedetail();


                            using (IDbConnection dbConnection = ConnectionBase.Connection)
                            {
                                dbConnection.Open();
                                DynamicParameters param = new DynamicParameters();
                                // param.Add("lotid", dbType: DbType.Int64, value: Convert.ToInt64(batchdetails.lotid), direction: ParameterDirection.Input);
                                var lotdata = new
                                {
                                    lotid = Convert.ToInt64(batchdetails.lotid),
                                };
                                string lotinput = JsonConvert.SerializeObject(lotdata);
                                param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                                param.Add("mode_p", dbType: DbType.String, value: "getbylotid", direction: ParameterDirection.Input);
                                var getTransid = dbConnection.Query<string>("public.splotmasterselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                                if (getTransid != null)
                                {
                                    var i1_tranid = JsonConvert.DeserializeObject<object>(getTransid.ToString());
                                    JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                                    JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                                    jsonchap.chaptertypename = obj1_tranid["chaptertypename"].ToString();


                                    if (jsonchap.chaptertypename.ToLower() != "chapter")
                                    {
                                        // if isprocessed == false, then the following
                                        // long jobwID = Convert.ToInt64(jobflowid1[0].ToString());

                                        var data = new { jobid = postdata[0].jobid };

                                        string input = JsonConvert.SerializeObject(data);
                                        var jobflowid1 = CommonRepository.ExecuteSP_ReturnList2("spjobworkflowdefinitionselect", input, "getbyjobidandstagetype");
                                        if (jobflowid1 != null)
                                        {


                                            var next_ordernodata1 = JsonConvert.DeserializeObject<object>(jobflowid1.ToString());
                                            JArray dt = JArray.Parse(next_ordernodata1.ToString());
                                            JObject obj1_jobid = JObject.Parse(dt[0].ToString());
                                            jobflowid1 = obj1_jobid["jobworkflowid"].ToString();
                                        }


                                        if (jobflowid1 != null)
                                        {
                                            long jobwID = Convert.ToInt64(jobflowid1.ToString());
                                            string lstatus = "R";
                                            SelectQueryForLot = "select * from lot_transaction Where jobworkflowid = " + jobwID + " and lotid = " + batchdetails.lotid + "  and lotstatus ='R'";
                                            writer1.WriteLine("SelectQueryForLot:" + SelectQueryForLot);
                                            string statusoffmbmmove = Fmbmmove(jobwID, batchdetails.lotid, lstatus, writer1, createdBy);
                                            if (statusoffmbmmove != "success")
                                            {
                                                writer1.WriteLine("Message :" + statusoffmbmmove + Environment.NewLine + "SelectQueryForLot:" + SelectQueryForLot + Environment.NewLine +
                                            "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                                                writer1.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return lotids;
        }
        public string iSProcessedLot(int lotid, int jobid, int userid)
        {
            try
            {
                //1. get Transactionid
                string transid = "", maxSequence = "";
                //using (DBContext db1 = new DBContext())
                //{
                //    BLDatamanipulation _db = new BLDatamanipulation();
                //    Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@lotid", Convert.ToInt64(lotid)) };
                //    var getTransid = _db.GetDataTable(db1, "select max(transactionid) as transactionid from lot_transaction where lotid = @lotid;", sParams);
                //    transid = getTransid.Rows[0]["transactionid"].ToString();
                //}

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    // param.Add("lotid", dbType: DbType.Int64, value: Convert.ToInt64(lotid), direction: ParameterDirection.Input);

                    var lotdata = new
                    {
                        lotid = Convert.ToInt64(lotid),
                    };
                    string lotinput = JsonConvert.SerializeObject(lotdata);
                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                    param.Add("mode_p", dbType: DbType.String, value: "getmaxransactionid", direction: ParameterDirection.Input);

                    // param.Add("p_option", dbType: DbType.String, value: "getmaxransactionid", direction: ParameterDirection.Input);
                    var getTransid = dbConnection.Query<string>("public.splottransactionselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();

                    if (getTransid != null)
                    {
                        var i1_tranid = JsonConvert.DeserializeObject<object>(getTransid.ToString());
                        JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                        JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                        transid = obj1_tranid["transactionid"].ToString();
                    }
                }



                //2. get Initial sequence //"sequence": 3,
                //Prasanth Code wrong validation added
                //int getsequence = Convert.ToInt32(cdata.sequence);
                ////is processed should be selected only word submission stage
                int getsequence = 3;
                //var chpdetails = db.Database.SqlQuery<jsonvalue>("SELECT json_build_object('transactionid', LM.stageorder) as json FROM job_workflow_master LM " +
                //    "LEFT JOIN lot_transaction CTM ON LM.jobworkflowid = CTM.jobworkflowid WHERE CTM.transactionid = @transactionid", new Npgsql.NpgsqlParameter { ParameterName = "@transactionid", Value = transid }).ToList();

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    // param.Add("transid", dbType: DbType.Int64, value: Convert.ToInt64(jobid), direction: ParameterDirection.Input);
                    // param.Add("p_option", dbType: DbType.String, value: "SW", direction: ParameterDirection.Input);

                    var jobiddata = new
                    {
                        transactionid = Convert.ToInt64(transid),
                    };
                    string lotinput = JsonConvert.SerializeObject(jobiddata);
                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                    param.Add("mode_p", dbType: DbType.String, value: "getstageorder", direction: ParameterDirection.Input);

                    var chpdetails = dbConnection.Query<string>("public.spjobworkflowdefinitionselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();


                    if (chpdetails != null)
                    {
                        var i1_tranid = JsonConvert.DeserializeObject<object>(chpdetails.ToString());
                        JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                        JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                        getsequence = (int)obj1_tranid["stageorder"];
                    }

                    // chaptertypedetail jsonchap = JsonConvert.DeserializeObject<chaptertypedetail>(chpdetails[0].json);
                    //  getsequence = Convert.ToInt32(jsonchap.transactionid);
                }
                ////3. get Max sequence
                //using (DBContext dbMax = new DBContext())
                //{
                //    BLDatamanipulation db2 = new BLDatamanipulation();
                //    Npgsql.NpgsqlParameter[] sParams2 = { new Npgsql.NpgsqlParameter("@jobid", jobid), new Npgsql.NpgsqlParameter("@lotid", lotid) };
                //    var getMaxSequence = db2.GetDataTable(dbMax, "select M.stageorder as maxSequence from job_workflow_master M inner join lot_master lt on lt.jobid=M.jobid where M.active = 1 and M.stagename_alias ='Supplement Creation' and M.jobid=@jobid and lt.lotid=@lotid limit 1;", sParams2);
                //    maxSequence = getMaxSequence.Rows[0]["maxSequence"].ToString();
                //}

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    //param.Add("jobid", dbType: DbType.Int64, value: Convert.ToInt64(jobid), direction: ParameterDirection.Input);
                    //param.Add("lotid", dbType: DbType.Int64, value: Convert.ToInt64(lotid), direction: ParameterDirection.Input);
                    //param.Add("p_option", dbType: DbType.String, value: "SW", direction: ParameterDirection.Input);

                    var jobiddata = new
                    {
                        jobid = Convert.ToInt64(jobid),
                        lotid = Convert.ToInt64(lotid),
                    };
                    string lotinput = JsonConvert.SerializeObject(jobiddata);
                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                    param.Add("mode_p", dbType: DbType.String, value: "getmaxSequence", direction: ParameterDirection.Input);

                    maxSequence = dbConnection.Query<string>("public.spjobworkflowdefinitionselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }


                //4. get Parameter 'SW'
                //Main Process
                string getResult = "";
                if (transid != "" && getsequence > 0 && maxSequence != "")
                {
                    //using (DBContext dbNew = new DBContext())
                    //{
                    //    var menudetails = dbNew.Database.SqlQuery<Int64>("select * from job_back_forwad(@p_tranid,@p_fromorder,@p_toorder,@p_option) as json",
                    //    new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = Convert.ToInt64(transid) },
                    //    new Npgsql.NpgsqlParameter { ParameterName = "@p_fromorder", Value = Convert.ToInt64(getsequence) },
                    //    new Npgsql.NpgsqlParameter { ParameterName = "@p_toorder", Value = Convert.ToInt16(maxSequence) },
                    //    new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "SW" }).ToList();
                    //    getResult = menudetails[0].ToString();
                    //}

                    using (IDbConnection dbConnection = ConnectionBase.Connection)
                    {
                        dbConnection.Open();
                        DynamicParameters param = new DynamicParameters();
                        param.Add("p_tranid", dbType: DbType.Int64, value: Convert.ToInt64(transid), direction: ParameterDirection.Input);
                        param.Add("p_fromorder", dbType: DbType.Int64, value: Convert.ToInt64(getsequence), direction: ParameterDirection.Input);
                        param.Add("p_toorder", dbType: DbType.Int16, value: Convert.ToInt16(maxSequence), direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: "SW", direction: ParameterDirection.Input);
                        getResult = dbConnection.Query<string>("public.spjobbackforward", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    }

                }




                ////5. Updating Pickedby in lot_transaction
                //using (DBContext dbUpdateTrans = new DBContext())
                //{
                //    int pickedby = Convert.ToInt32(HttpContext.Current.Session["UserID"].ToString());
                //    int getTransid = Convert.ToInt32(getResult);
                //    BLDatamanipulation db22 = new BLDatamanipulation();
                //    Npgsql.NpgsqlParameter[] sParams22 = { new Npgsql.NpgsqlParameter("@pickedby", pickedby), new Npgsql.NpgsqlParameter("@transactionid", getTransid) };
                //    var getMaxSequence = db22.GetDataTable(dbUpdateTrans, "update lot_transaction set pickedby=@pickedby where transactionid=@transactionid;", sParams22);


                //}

                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    int getTransid = Convert.ToInt32(getResult);
                    int pickedby = userid;
                    param.Add("p_tranid", dbType: DbType.Int32, value: Convert.ToInt32(getTransid), direction: ParameterDirection.Input);
                    param.Add("p_userid", dbType: DbType.Int32, value: Convert.ToInt32(pickedby), direction: ParameterDirection.Input);
                    param.Add("p_option", dbType: DbType.String, value: "updatepickedby", direction: ParameterDirection.Input);
                    param.Add("p_status", dbType: DbType.String, value: "", direction: ParameterDirection.Input);
                    var Checkinapp = dbConnection.Query<string>("public.spusrlottranupdatev1", param, commandType: CommandType.StoredProcedure).ToList();

                }
                return "SP-job_back_forwad:(" + getResult + "," + getsequence + "," + maxSequence + ",SW," + userid + ")";
            }
            catch (Exception ex)
            {
                return "SP-Pick Lots Failed :( Lotid " + lotid + " jobid " + jobid + "error " + ex.Message.ToString() + ")";
            }
        }

        public bool isSupplementProcessed(string jobid)
        {
            // BLDatamanipulation db1 = new BLDatamanipulation();
            // BLDatamanipulation db2 = new BLDatamanipulation();
            // Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@jobid", jobid) };
            // Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@jobid1", jobid) };
            string json = "";

            //  using (DBContext db = new DBContext())
            //  {
            // List<processlotstatus> processlotstatuses = new List<processlotstatus>();
            //supplement stage 
            //var processlots = db1.GetDataTable(db, "select jbwrkflwmst.jobid,jbwrkflwmst.stageorder as stageorder, ltbch.batchid, lottrans.jobworkflowid,ltbchdt.lotid from lot_transaction lottrans " +
            //    "left outer join lot_batch_details ltbchdt on ltbchdt.lotid = lottrans.lotid  or ltbchdt.batchid = lottrans.batchid " +
            //    "left outer join lot_batch ltbch on ltbch.batchid = ltbchdt.batchid and ltbch.active = 1 " +
            //    "left outer join job_master jm on jm.jobid = ltbch.jobid " +
            //    "left outer join job_workflow_master jbwrkflwmst on lottrans.jobworkflowid = jbwrkflwmst.jobworkflowid  " +
            //    " where jm.jobid = @jobid and jbwrkflwmst.stagename_alias = 'Supplement Creation'  and lottrans.lotstatus = 'C'", sParams);


            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                DynamicParameters param = new DynamicParameters();
                var lotdata = new
                {
                    jobid = jobid,
                };
                string lotinput = JsonConvert.SerializeObject(lotdata);
                param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "getbyjobid", direction: ParameterDirection.Input);
                var processlots = dbConnection.Query<string>("public.splottransactionselect", param, commandType: CommandType.StoredProcedure).ToList();

                if (processlots.Count() > 0 && processlots.ToList()[0] != null)
                {

                    var next_ordernodata2 = JsonConvert.DeserializeObject<object>(processlots.ToString());
                    JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

                    if (dt_order.Count > 0)
                    {
                        for (int i = 0; i <= dt_order.Count - 1; i++)
                        {
                            string jobworkflowid = dt_order[i]["jobworkflowid"].ToString();
                            // Npgsql.NpgsqlParameter[] sParams2 = { new Npgsql.NpgsqlParameter("@jobworkflowid", jobworkflowid) };
                            // var dt1 = db1.GetDataTable(db, "update lot_transaction set lotstatus = 'W' where jobworkflowid =  @jobworkflowid", sParams2);

                            var lotdata2 = new
                            {
                                status = 'W',
                                jobworkflowid = jobworkflowid,
                                p_option = "lotstatusUpdatebyjobwfid"
                            };
                            string lotinput2 = JsonConvert.SerializeObject(lotdata2);
                            param.Add("inputjsonstr", dbType: DbType.String, value: lotinput2, direction: ParameterDirection.Input);
                            dbConnection.Query<string>("public.spusrlottransactionupdate", param, commandType: CommandType.StoredProcedure).FirstOrDefault();



                        }
                        //After supplement
                        //var processlots1 = db2.GetDataTable(db, "select jwm.stagename_alias,jwm.jobworkflowid,lt.transactionid from  job_workflow_master jwm  " +
                        //    "left join job_master jm on jm.jobid = jwm.jobid " +
                        //    "left join lot_transaction lt on lt.jobworkflowid = jwm.jobworkflowid WHERE jwm.stageorder > 25 and jm.jobid = @jobid1", sParams1);


                        var lotdata1 = new
                        {
                            jobid = jobid,
                        };
                        string lotinput1 = JsonConvert.SerializeObject(lotdata1);
                        param.Add("inputjsonstr", dbType: DbType.String, value: lotinput1, direction: ParameterDirection.Input);
                        param.Add("mode_p", dbType: DbType.String, value: "getbyjobidandstage", direction: ParameterDirection.Input);
                        var processlots3 = dbConnection.Query<string>("public.spjobworkflowdefinitionselect", param, commandType: CommandType.StoredProcedure).ToList();
                        var next_ordernodata3 = JsonConvert.DeserializeObject<object>(processlots3.ToString());
                        JArray dt_order3 = JArray.Parse(next_ordernodata3.ToString());

                        if (dt_order3.Count > 0)
                        {
                            for (int i = 0; i <= dt_order3.Count - 1; i++)
                            {
                                if (!string.IsNullOrEmpty(dt_order3[i]["transactionid"].ToString()))
                                {
                                    string transactionid = dt_order3[i]["transactionid"].ToString();
                                    // Npgsql.NpgsqlParameter[] sParams3 = { new Npgsql.NpgsqlParameter("@transactionid", transactionid) };
                                    // var dt1 = db2.GetDataTable(db, "update lot_transaction set lotstatus = 'B' where transactionid =  @transactionid", sParams3);

                                    var lotdata2 = new
                                    {
                                        status = 'B',
                                        transactionid = transactionid,
                                        p_option = "lotstatusUpdatebytranid"
                                    };
                                    string lotinput2 = JsonConvert.SerializeObject(lotdata2);
                                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput2, direction: ParameterDirection.Input);
                                    dbConnection.Query<string>("public.spusrlottransactionupdate", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                                }
                            }
                        }
                        return true;
                    }
                    else
                    {
                        //for (int i = 0; i < processlots.Rows.Count; i++)
                        //{
                        //    processlotstatuses.Add(new processlotstatus() { satgestatus = processlots.Rows[i]["lotstatus"].ToString(), stagename = processlots.Rows[i]["stagename_alias"].ToString() });
                        //}
                        //var jsonSerialiser = new JavaScriptSerializer();
                        return false; //jsonSerialiser.Serialize(processlotstatuses);
                    }
                }
                else
                {
                    return false;
                }
            }
            //  }
        }

        public string Fmbmmove(long jobwID, long lids, string lstatus, StreamWriter writer1, int createdby)
        {
            try
            {
                // BLDatamanipulation db1 = new BLDatamanipulation();
                // Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@p_jwid", jobwID), new Npgsql.NpgsqlParameter("@lid", lids), new Npgsql.NpgsqlParameter("@lsstatus", lstatus) };
                // var usrLottranDetails = db1.GetDataTable(db, "select * from lot_transaction Where jobworkflowid = @p_jwid and lotid = @lid and lotstatus =@lsstatus", sParams1);


                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    // param.Add("jobworkflowid", dbType: DbType.Int32, value: Convert.ToInt32(jobwID), direction: ParameterDirection.Input);
                    // param.Add("lotid", dbType: DbType.Int32, value: Convert.ToInt32(lids), direction: ParameterDirection.Input);
                    // param.Add("lotstatus", dbType: DbType.String, value: lstatus, direction: ParameterDirection.Input);

                    var lotdata = new
                    {
                        jobworkflowid = Convert.ToInt32(jobwID),
                        lotid = Convert.ToInt32(lids)
                    };
                    string lotinput = JsonConvert.SerializeObject(lotdata);
                    param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);

                    param.Add("mode_p", dbType: DbType.String, value: "gettransactionidbystatus", direction: ParameterDirection.Input);
                    var list_tranid = dbConnection.Query<string>("public.splottransactionselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                    if (list_tranid != null)
                    {
                        var i1_tranid = JsonConvert.DeserializeObject<object>(list_tranid.ToString());
                        JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                        JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                        string tranid = obj1_tranid["transactionid"].ToString();

                        //  string tranid = usrLottranDetails.Rows[0]["transactionid"].ToString();
                        // Tranfer the files into Server 
                        writer1.WriteLine(Environment.NewLine + "Filemovement Start-------------");
                        Filemovement(tranid, createdby.ToString(), writer1);
                        writer1.WriteLine("Filemovement Complete-----------" + Environment.NewLine + Environment.NewLine);
                    }
                }
                return "success";
            }
            catch (Exception ex)
            {
                writer1.WriteLine(Environment.NewLine + "Error Messsge:" + ex.Message.ToString());
                return "failed:" + "Error Messsge:" + ex.Message.ToString();
            }
        }

        public object Filemovement(string tranid, string pickedby, StreamWriter writer1)
        {
            try
            {
                writer1.WriteLine("Start the Filemovement for TranID:" + tranid + "," + "UserID:" + pickedby);
                // ServerInfo servinfo = new ServerInfo();
                string serverpath = oCommonRepository.GetServerPath(tranid, "serverinfo", true);
                // string serverpath = servinfo.GetServerPath(tranid, true, "serverinfo");
                //var usr_lot_tran_update = db.Database.SqlQuery<jsonvalue>("select * from  usr_lot_tran_update(@p_userid, @p_tranid,@p_holdreason,@p_option) as json",
                //new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = pickedby },
                //new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = tranid },
                //new Npgsql.NpgsqlParameter { ParameterName = "@p_holdreason", Value = "" },
                //new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "checkout_" }).ToList();
                //var obj1 = JsonConvert.DeserializeObject<resultvalue>(usr_lot_tran_update[0].json);

                long Transid = 0;
                lottriger obj = new lottriger();
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    DynamicParameters param = new DynamicParameters();
                    param.Add("p_tranid", dbType: DbType.Int32, value: Convert.ToInt32(tranid), direction: ParameterDirection.Input);
                    param.Add("p_userid", dbType: DbType.Int32, value: Convert.ToInt32(pickedby), direction: ParameterDirection.Input);
                    param.Add("p_status", dbType: DbType.String, value: "", direction: ParameterDirection.Input);
                    param.Add("p_option", dbType: DbType.String, value: "checkout_", direction: ParameterDirection.Input);
                    var Checkinapp = dbConnection.Query<string>("public.spusrlottranupdatev1", param, commandType: CommandType.StoredProcedure).ToList();
                    if (Checkinapp != null)
                    {
                        oCommonRepository.WriteLog("SendMq_WorkArea", Checkinapp[0].ToString());
                        var next_ordernodata10 = JsonConvert.DeserializeObject<object>(Checkinapp[0].ToString());
                        JObject dtparallelnextstage10 = JObject.Parse(next_ordernodata10.ToString());
                        string Transids = dtparallelnextstage10["tranid"].ToString();

                        if (Transids != null)
                        {
                            Transid = Int64.Parse(Transids);
                        }
                    }


                    using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(Transid.ToString()))
                    {
                        string serverpath_ = oCommonRepository.GetServerPath(Transid.ToString(), "serverinfo", true);
                        writer1.WriteLine("ServerPath : " + serverpath_);
                        string serverpath_prev_ = oCommonRepository.GetServerPath(tranid, "serverinfo", false);
                        writer1.WriteLine("Previous ServerPath : " + serverpath_prev_);

                        System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(System.IO.Path.Combine(serverpath_prev_, "IN"));
                        string wordfile = "";
                        writer1.WriteLine("Files Copy from : " + serverpath_prev_ + " to " + serverpath_);
                        writer1.WriteLine("---------------" + Environment.NewLine);
                        foreach (System.IO.FileInfo fle in dirinfo.GetFiles("*.*"))
                        {
                            if (System.IO.File.Exists(Path.Combine(serverpath_, "IN", fle.Name)))
                                System.IO.File.Delete(Path.Combine(serverpath_, "IN", fle.Name));

                            if (!fle.Name.ToString().ToLower().Contains("thumb.db"))
                            {
                                fle.CopyTo(System.IO.Path.Combine(serverpath_, "IN", fle.Name), true);
                                writer1.WriteLine("FileName : " + System.IO.Path.Combine(serverpath_, "IN", fle.Name) + "<br/>");
                            }
                        }
                        writer1.WriteLine("---------------" + Environment.NewLine);
                    }
                }
                return "success";
            }
            catch (Exception ex)
            {
                return "error" + ":" + ex.Message;
            }

        }
        private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            try
            {

                // Get the subdirectories for the specified directory.
                DirectoryInfo dir = new DirectoryInfo(sourceDirName);

                if (!dir.Exists)
                {
                    return;
                    //throw new DirectoryNotFoundException(
                    //    "Source directory does not exist or could not be found: "
                    //    + sourceDirName);
                }

                DirectoryInfo[] dirs = dir.GetDirectories();
                // If the destination directory doesn't exist, create it.
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }

                // Get the files in the directory and copy them to the new location.
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    string temppath = Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                }

                // If copying subdirectories, copy them and their contents to new location.
                if (copySubDirs)
                {
                    foreach (DirectoryInfo subdir in dirs)
                    {
                        string temppath = Path.Combine(destDirName, subdir.Name);
                        DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                    }
                }
            }
            catch (Exception ex)
            {
                string filePath1 = @"E:\webapps\lapstest\MailError.txt";

                using (StreamWriter writer = new StreamWriter(filePath1, true))
                {
                    writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                       "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                    writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                }



            }
        }

        //Code to add new record
        [Authorize]
        [HttpPost("MovetoPagination")]
        public IActionResult MovetoPagination(List<lotmasterModel> olotmaster)
        {
            try
            {
                foreach (var item in olotmaster)
                {
                    string inputstr = JsonConvert.SerializeObject(item);
                    var checkout = getCheckout(item.transactionid.ToString(), item.createdby.ToString(), "C", "checkout_only", item.jobworkflowid.ToString(), "");
                    string jobworkflowid = "";
                    using (IDbConnection dbConnection = ConnectionBase.Connection)
                    {
                        dbConnection.Open();
                        DynamicParameters param = new DynamicParameters();
                        var lotdata = new
                        {
                            jobworkflowid = Convert.ToInt32(item.jobworkflowid.ToString()),
                        };
                        string lotinput = JsonConvert.SerializeObject(lotdata);
                        param.Add("inputjsonstr", dbType: DbType.String, value: lotinput, direction: ParameterDirection.Input);
                        param.Add("mode_p", dbType: DbType.String, value: "getdetailsbyjobworkflowid", direction: ParameterDirection.Input);
                        var list_tranid = dbConnection.Query<string>("public.splottransactionselect", param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                        if (list_tranid != null)
                        {
                            var i1_tranid = JsonConvert.DeserializeObject<object>(list_tranid.ToString());
                            JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
                            JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
                            jobworkflowid = obj1_tranid["jobworkflowid"].ToString();
                        }
                        var checkout_next = getCheckout(item.transactionid.ToString(), item.createdby.ToString(), "R", "checkout_next", jobworkflowid, "", item.lotid.ToString());
                    }
                }
                return Ok();
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }



        public static List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "", string lotid = "0")
        {
            CommonRepository oCommonRepository = new CommonRepository();
            var data = new { p_tranid = trans_id, p_userid = p_userid, p_status = status, p_option = option, n_jobworkflowid = jobworkflowid, p_comments = p_comments, n_lotid = lotid };
            var jsonstr = JsonConvert.SerializeObject(data);
            var Checkinapp = oCommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);
            System.Collections.Generic.List<jsonvalue> appdetails1 = new List<jsonvalue>();
            jsonvalue dd = new jsonvalue();
            dd.json = Checkinapp.ToString();
            appdetails1.Add(dd);
            return appdetails1;
        }


        [Authorize]
        [HttpGet("ExportWordFile/{tranid}/{filename}/{projectdid}/{stagenm}/{projectid}/{userid}/{lotkey}")]
        public object ExportWordFile(int tranid, string filename, int projectdid, string stagenm, int projectid, int userid, string lotkey)
        {
            string wordFilePath = string.Empty;
            int retval = 0;
            try
            {
                string serverinfo = oCommonRepository.GetServerPath(tranid.ToString(), "serverinfo", false);
                string strindir = Startup.Configuration.GetValue<string>("AppSettings:serverinfolder");
                string stroutdir = Startup.Configuration.GetValue<string>("AppSettings:serveroutfolder");
                string serverworkingpath = Path.Combine(serverinfo, stroutdir);
                string filetosave = filename + ".html";
                string xmlFileName = filename + ".xml";
                string filepath = Path.Combine(serverworkingpath, filetosave);
                string localXMLFilePath = string.Empty;
                string QueryFilePath = Path.Combine(serverworkingpath, filename + ".qry");
                //string wordpassword = Startup.Configuration.GetValue<string>("AppSettings:wordpassword");
                string wordpassword = lotkey;
                string sreloclocation = ""; string OulineXMLFileLocalPath = string.Empty; string QueryFileLocalPath = string.Empty; string ExportWordPath = string.Empty;
                string ExportWordFilePath = "";
                if (isWindowsWK)
                {
                    sreloclocation = Path.Combine(localpathwindows, "Temp", "H2W", tranid.ToString());
                    OulineXMLFileLocalPath = Path.Combine(XMLFilepathwindows, tranid.ToString());
                    ExportWordFilePath = Path.Combine(localpathwindows, "Temp", "export", lotkey.ToString());
                }
                else
                {
                    sreloclocation = Path.Combine(localpathlinux, "Temp", "H2W", tranid.ToString());
                    OulineXMLFileLocalPath = Path.Combine(XMLFilepathlinux, tranid.ToString());
                    ExportWordFilePath = Path.Combine(exportwordfilepathlinux, lotkey.ToString());
                }
                if (!Directory.Exists(sreloclocation))
                {
                    Directory.CreateDirectory(sreloclocation);
                }
                if (System.IO.File.Exists(Path.Combine(sreloclocation, "Export.log")))
                {
                    System.IO.File.Delete(Path.Combine(sreloclocation, "Export.log"));
                }
                WriteExportImportLog(sreloclocation, "Export.log", "Export Start....\r\n");
                // var res = GetMainTemplate(projectdid, stagenm, projectid, filename, "", tranid.ToString(), false, "H2W");
                WriteExportImportLog(sreloclocation, "Export.log", "Outline XML Generated");
                string localHTMLFilePath = Path.Combine(sreloclocation, filetosave);
                OulineXMLFileLocalPath = Path.Combine(sreloclocation, filename + "_outline.xml");
                QueryFileLocalPath = Path.Combine(sreloclocation, filename + ".qry");
                if (System.IO.File.Exists(filepath))
                {
                    if (System.IO.File.Exists(localHTMLFilePath))
                    {
                        System.IO.File.Delete(localHTMLFilePath);
                    }
                    System.IO.FileInfo fi1 = new System.IO.FileInfo(filepath);
                    fi1.CopyTo(localHTMLFilePath);
                    WriteExportImportLog(sreloclocation, "Export.log", "HTML File copied to local working directory.");
                    string alltxt = System.IO.File.ReadAllText(localHTMLFilePath);
                    alltxt = Regex.Replace(alltxt, "&nbsp;", " ");
                    alltxt = Regex.Replace(alltxt, "cke_editable cke_editable_inline cke_contents_ltr", "cke_editable");
                    alltxt = Regex.Replace(alltxt, "cke_editable ICE-Tracking", "cke_editable");
                    alltxt = Regex.Replace(alltxt, "cke_editable cke_focus", "cke_editable");
                    alltxt = Regex.Replace(alltxt, "<br>", "");
                    System.IO.File.WriteAllText(localHTMLFilePath, alltxt);
                    if (System.IO.File.Exists(QueryFilePath))
                    {
                        if (System.IO.File.Exists(QueryFileLocalPath))
                        {
                            System.IO.File.Delete(QueryFileLocalPath);
                        }
                        System.IO.FileInfo fi2 = new System.IO.FileInfo(QueryFilePath);
                        fi2.CopyTo(QueryFileLocalPath);
                        WriteExportImportLog(sreloclocation, "Export.log", "Query File copied to local working directory.");
                    }
                    //converting the html file to xml file
                    string exePath = ""; string localpath = ""; string args = string.Empty; string KLIConverterExePath = string.Empty;
                    if (isWindowsWK)
                    {
                        localpath = localpathwindows;
                    }
                    else
                    {
                        localpath = localpathlinux;
                    }
                    exePath = Path.Combine(localpath, "Converters", "html2xml", "html2xml.dll");
                    KLIConverterExePath = Path.Combine(localpath, "Converters", "KLI_XTW_CORE", "KLI_XTW_CORE.dll");

                    var data = new
                    {
                        errormessage = exePath.ToString(),
                        createdby = 0,
                        controller = "WorkAreaApi:html to xml transformation - localpath"
                    };
                    retval = oCommonRepository.addlog(data, "errorlog");
                    try
                    {
                        if (System.IO.File.Exists(exePath))
                        {
                            args = "\"" + exePath + "\" \"" + localHTMLFilePath + "\" false"; ;
                            WriteExportImportLog(sreloclocation, "Export.log", "HTML to XML Conversion start..");
                            WriteExportImportLog(sreloclocation, "Export.log", "H2X exe file with location: " + exePath);
                            WriteExportImportLog(sreloclocation, "Export.log", "H2X output file: " + args);
                            System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                            procInfo.StartInfo.WorkingDirectory = localpath;
                            procInfo.StartInfo.CreateNoWindow = true;
                            procInfo.StartInfo.UseShellExecute = false;
                            procInfo.StartInfo.RedirectStandardError = true;
                            procInfo.StartInfo.FileName = "dotnet";// exePath;
                            procInfo.StartInfo.Arguments = args;
                            procInfo.Start();
                            data = new
                            {
                                errormessage = (exePath + " " + args).ToString(),
                                createdby = 0,
                                controller = "WorkAreaApi: html to xmlTransformation - run command"
                            };
                            retval = oCommonRepository.addlog(data, "errorlog");
                            string proError = procInfo.StandardError.ReadToEnd();
                            procInfo.WaitForExit();
                            WriteExportImportLog(sreloclocation, "Export.log", "HTML to XML Conversion finished..\r\n");
                        }
                        localXMLFilePath = Path.Combine(sreloclocation, xmlFileName);
                        if (System.IO.File.Exists(localXMLFilePath))
                        {
                            WriteExportImportLog(sreloclocation, "Export.log", "H2X output file: " + args + ", present..");
                            string XMLToWordArg = string.Empty;
                            //  XMLToWordArg = localXMLFilePath;
                            if (!System.IO.File.Exists(QueryFileLocalPath))
                            {
                                QueryFileLocalPath = "";
                            }
                            if (!System.IO.File.Exists(OulineXMLFileLocalPath))
                            {
                                OulineXMLFileLocalPath = "";
                                data = new
                                {
                                    errormessage = (XMLToWordArg).ToString(),
                                    createdby = 0,
                                    controller = "WorkAreaApi: xml to word Transformation "
                                };
                                retval = oCommonRepository.addlog(data, "errorlog");
                                return new conres { status = false, res = "Failed: Ouline XML File is not Present", file = null };
                            }

                            try
                            {
                                if (System.IO.File.Exists(KLIConverterExePath))
                                {
                                    XMLToWordArg = "\"" + KLIConverterExePath + "\" \"" + localXMLFilePath + "\" \"" + QueryFileLocalPath + "\" \"" + OulineXMLFileLocalPath + "\" \"" + wordpassword + "\"";
                                    WriteExportImportLog(sreloclocation, "Export.log", "XML to Word Conversion start..");
                                    WriteExportImportLog(sreloclocation, "Export.log", "X2W exe file with location: " + KLIConverterExePath);
                                    WriteExportImportLog(sreloclocation, "Export.log", "X2W conversion parameter: " + XMLToWordArg);
                                    System.Diagnostics.Process procInfo = new System.Diagnostics.Process();
                                    procInfo.StartInfo.WorkingDirectory = localpath;
                                    procInfo.StartInfo.CreateNoWindow = true;
                                    procInfo.StartInfo.UseShellExecute = false;
                                    procInfo.StartInfo.RedirectStandardError = true;
                                    procInfo.StartInfo.FileName = "dotnet";// KLIConverterExePath;
                                    procInfo.StartInfo.Arguments = XMLToWordArg;
                                    procInfo.Start();
                                    data = new
                                    {
                                        errormessage = (KLIConverterExePath + " " + XMLToWordArg).ToString(),
                                        createdby = 0,
                                        controller = "WorkAreaApi: xml to  word Transformation - run command"
                                    };
                                    retval = oCommonRepository.addlog(data, "errorlog");
                                    string proError = procInfo.StandardError.ReadToEnd();
                                    procInfo.WaitForExit();
                                    WriteExportImportLog(sreloclocation, "Export.log", "XML to Word Conversion end..\r\n");
                                }
                                //  wordFilePath = Path.Combine(sreloclocation, "output", filename + ".docx");
                                wordFilePath = Path.Combine(sreloclocation, "output");

                            }
                            catch (Exception ex)
                            {
                                data = new
                                {
                                    errormessage = ex.Message.ToString(),
                                    createdby = 0,
                                    controller = "WorkAreaApi: xml to wordTransformation -  ex.Message"
                                };
                                retval = oCommonRepository.addlog(data, "errorlog");
                                oCommonRepository.WriteLog(ex.Message, "WorkAreaApi/xml to word Transformation -Error log ");
                                WriteExportImportLog(sreloclocation, "Export.log", "X2W conversion failed: " + ex.Message);
                                return new conres { status = false, res = "Failed to Export. X2W conversion failed.", file = null };
                            }
                        }
                        else
                        {
                            data = new
                            {
                                errormessage = "XML file not generated",
                                createdby = 0,
                                controller = "WorkAreaApi:html to xml Transformation"
                            };
                            retval = oCommonRepository.addlog(data, "errorlog");
                            oCommonRepository.WriteLog("XML file not generated", "WorkAreaApi / html to xml Transformation -Error log ");
                            WriteExportImportLog(sreloclocation, "Export.log", "H2X conversion failed: XML file not generated");
                            return new conres { status = false, res = "Failed to Export: XML file not found.", file = null };
                        }
                    }
                    catch (Exception ex)
                    {
                        data = new
                        {
                            errormessage = ex.Message.ToString(),
                            createdby = 0,
                            controller = "WorkAreaApi:html to xml Transformation -  ex.Message"
                        };
                        retval = oCommonRepository.addlog(data, "errorlog");
                        oCommonRepository.WriteLog(ex.Message, "WorkAreaApi/ html to xmlTransformation -Error log ");
                        WriteExportImportLog(sreloclocation, "Export.log", "H2X conversion failed");
                        return new conres { status = false, res = "Failed to Export. Issue in Conversion.", file = null };
                    }
                }

                string ExportWordFile = "";
                byte[] fileBytes = null;
                string wordfile = Path.Combine(wordFilePath, filename + ".docx");
                if (System.IO.File.Exists(wordfile))
                {
                    WriteExportImportLog(sreloclocation, "Export.log", "Exported Word File Location: " + ExportWordFilePath);
                    if (!Directory.Exists(ExportWordFilePath))
                    {
                        Directory.CreateDirectory(ExportWordFilePath);
                    }
                    ExportWordFile = Path.Combine(ExportWordFilePath, filename + ".docx");
                    if (System.IO.File.Exists(ExportWordFile))
                    {
                        System.IO.File.Delete(ExportWordFile);
                    }
                    System.IO.FileInfo fi2 = new System.IO.FileInfo(wordfile);
                    fi2.CopyTo(ExportWordFile);
                    WriteExportImportLog(sreloclocation, "Export.log", "Word File moved to exported location.");
                }
                else
                {
                    WriteExportImportLog(sreloclocation, "Export.log", "Word File not present, H2W conversion failed.");
                }
                if (ExportWordFile != "")
                {
                    fileBytes = System.IO.File.ReadAllBytes(ExportWordFile);
                }
                else
                {
                    WriteExportImportLog(sreloclocation, "Export.log", "Imported file does not exist.");
                    return new conres { status = true, res = "Success", file = null };
                }
                lottraninfo lotdata = new lottraninfo();
                lotdata.p_tranid = tranid.ToString();
                lotdata.updatedby = userid;
                lotdata.islocked = true;
                var retData = _LotBatchService.UpdateIsLocked(lotdata);
                WriteExportImportLog(sreloclocation, "Export.log", "Export End....\r\n");
                WriteExportImportLog(sreloclocation, "Export.log", "editor locked for Import");

                return new conres { status = true, res = "Success", file = fileBytes };

            }
            catch (Exception ex)
            {
                var data = new
                {
                    errormessage = ex.Message.ToString(),
                    createdby = 0,
                    controller = "WorkAreaApi:html to xml Transformation -  ex.Message"
                };
                retval = oCommonRepository.addlog(data, "errorlog");
                oCommonRepository.WriteLog(ex.Message, "WorkAreaApi/ html to xmlTransformation -Error log ");
                return new conres { status = false, res = "Failed to Export." };
            }
        }
        private void WriteExportImportLog(string strpath, string filename, string strmsg)
        {
            string userlogfilename = Path.Combine(strpath, filename);
            using (StreamWriter writer = new StreamWriter(userlogfilename, true))
            {
                writer.WriteLine(strmsg);
                writer.Close();
            };
        }
        public class conres
        {
            public bool status { get; set; }
            public string res { get; set; }
            public byte[] file { get; set; }


        }
    }
}