namespace RequestService
{
    //using Microsoft.AspNetCore.SignalR.Client;
    using Dapper;
    using LAPS_WATCHER;
    using LAPS_WATCHER.App_Data;
    using LAPS_WATCHER.Configure;
    using LAPS_WATCHER.Messaging;
    using LAPS_WATCHER.Models;
    using MassTransit;
    using MassTransit.Logging;
    using MassTransit.Turnout.Contracts;
    using Message.MessageTypes;
    //using WK_KLI_LAPS_Service.App_Data;
    using Microsoft.AspNet.SignalR.Client;
    using Microsoft.Extensions.Configuration;
    //using WK_KLI_LAPS_Service.Models;
    using Microsoft.Extensions.Logging;
    using Microsoft.VisualBasic;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using RestSharp;
    using ServiceController;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Threading;
    using System.Threading.Tasks;
    using static LAPS_WATCHER.Messaging.RabbitMq;
    using appdetails = LAPS_WATCHER.Models.appdetails;
    using insertcomments = LAPS_WATCHER.Models.insertcomments;

    //using MassTransit.Logging;

    class RequestConsumer : IConsumer<PublishMessage>
    {
        CommonRepository oCommonRepository = new CommonRepository();

        // readonly ILog _log = Logger.Get<RequestConsumer>();
        public static string EXE_Path = CustomConfiguration.AppSettings.GetValue<string>("AppSettings:EXE_PATH");
        public static string Process_Path = CustomConfiguration.AppSettings.GetValue<string>("AppSettings:PROCESS_PATH");
        public static string fileName = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Log.txt");

        static public void WriteLog(string Module, string ErroMer, string tranid)
        {
            try { File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "//" + tranid + "_params.log", string.Join("", "\r\n Module - ", Module, "\tErrorMessage : ", ErroMer)); }
            catch (Exception ex) { }
        }

        public async Task Consume(ConsumeContext<PublishMessage> context)
        {
            //Console.WriteLine("Working");
            //await Console.Out.WriteLineAsync($"Received:{context}");
            string data = string.Concat("AppType: ", context.Message._AppType, ", Tranid: ", context.Message._TransId, ", StageType: ", context.Message._StageType, ", Flag: ", context.Message._Flag);
            CommonClass.laps2Log("Consumer Received Data: ", data);
            if (Global.isparallel == "1")
            {
                while (true)
                {
                    if (ThreadPoolAvailability() > 0)
                        break;
                }
                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessFile), context.Message);
            }
            else
            {
                ProcessFile(context.Message);
            }

        }
        private static int ThreadPoolAvailability()
        {
            ThreadPool.SetMaxThreads(Convert.ToInt32(Global.maxthread), Convert.ToInt32(Global.maxthread));
            int max, max2;
            ThreadPool.GetMaxThreads(out max, out max2);
            int available, available2;
            ThreadPool.GetAvailableThreads(out available, out available2);
            int running = max - available;
            Console.WriteLine("running:" + running.ToString());
            //Console.WriteLine("max:" + available.ToString());
            //Console.WriteLine("available:" + available.ToString());
            string strMessage =
               String.Format(@"running: {0} max: {1} available {2}",
                   running.ToString(),
                   max.ToString(),
                   available.ToString());
            Console.WriteLine(strMessage);
            return available;

        }
         static void ProcessFile(object fileNameObj)
        {
            try
            {
                Console.WriteLine("LAPS2 App Watcher ProcessFile method started");
                CommonClass.laps2Log("LAPS2 App Watcher", "ProcessFile method started");
                var sVal = (PublishMessage)fileNameObj;
                LapsExeParams p = new LapsExeParams();

                //p.AppType = "checkout_stage_withfile";
                //p.UserId = "264";
                //p.StageType = "server";
                //p.TransId = "211998";
                //p.Enviroment = "lnbpm_uat";
                //p.Flag = sVal._Flag;
                //p.Batch = sVal._Batch;
                //p.PublicationType = sVal._PublicationType;
                //p.PublicationID = sVal._PublicationID;
                //p.comment = sVal._comment;
                //p.DynamicList = sVal._DynamicList;
                //Global.Enviroinment = "lnbpm_uat";

                p.AppType = sVal._AppType;
                p.UserId = sVal._UserId;
                p.StageType = sVal._StageType;
                p.TransId = sVal._TransId;
                p.Enviroment = sVal._Enviroment;
                p.Flag = sVal._Flag;
                p.Batch = sVal._Batch;
                p.PublicationType = sVal._PublicationType;
                p.PublicationID = sVal._PublicationID;
                p.comment = sVal._comment;
                p.DynamicList = sVal._DynamicList;
                Global.Enviroinment = sVal._Enviroment;

                Console.WriteLine("LAPS2 App Watcher: AppType-" + p.AppType.ToString());
                Console.WriteLine("LAPS2 App Watcher: TransId-" + p.TransId.ToString());
                LoadFunction(p);
                Console.WriteLine("Thread Pool : " + p.AppType.ToString() + "    " + DateTime.Now.ToString());
                System.Threading.Thread.Sleep(1000);
                CommonClass.laps2Log("ProcessFile:AppTypeValue", p.AppType);
                WriteLog("Queue Started", p.TransId, p.Enviroment);
            }
            catch (Exception Ex)
            {
                CommonClass.ErrorLog(Ex);
            }


        }
        // static async Task LoadFunctionAsync(LapsExeParams p)
        static void LoadFunction(LapsExeParams p)
        {
            ServerInfo svrinfo = new ServerInfo();
            try
            {
                string Error = "";
                List<appdetails> appdetails = new List<appdetails>();
                appdetails = CommonClass.CheckAppType(p.TransId, p.UserId);
                if (appdetails.Count > 0)
                {
                    Console.WriteLine("App Details data getting: AppType- " + p.AppType);
                    //Server
                    var process_without_file = appdetails[0].process_without_file;
                    if (p.AppType == "checkout_stage_withfile_watcher")
                    {
                        Console.WriteLine("checkout_stage_withfile_watcher");
                        Console.WriteLine("RequestConsumer:getCheckout:checkout_stage_withfile_watcher");
                        //Check new concept********************
                        lot_tran_info lotinfo = new lot_tran_info();
                        lotinfo.p_tranid = p.TransId.ToString();
                        lotinfo.p_userid = p.UserId;
                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                        lotinfo.p_option = "checkout";
                        lotinfo.p_holdreason = "";
                        Checkout_transaction(lotinfo, "checkout_stage_withfile", p.Flag);
                        //*************************************
                    }
                    else if (p.AppType == "checkout_stage_withoutfile_watcher")
                    {
                        lot_tran_info lotinfo = new lot_tran_info();
                        lotinfo.p_tranid = p.TransId.ToString();
                        lotinfo.p_userid = p.UserId;
                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                        lotinfo.p_option = "checkout";
                        lotinfo.p_holdreason = "";
                        Checkout_transaction(lotinfo, "checkout_stage_withoutfile", p.Flag);
                    }
                    else if (p.AppType == "checkin_apps")
                    {
                        if (appdetails[0].checkin_appwather == "true")
                        {
                            CheckIn(p.TransId, p.UserId, "checkin", "P");
                            var output = Trigger_Watcher(p.TransId, p.UserId, "IN", appdetails[0].exe_path, p.Flag, p.AppType);
                            Console.WriteLine("watcher triggerred: ");
                        }
                        else
                        {
                            //Call Check In
                            CheckIn(p.TransId, p.UserId, "checkin", "P");
                            if (appdetails[0].checkin_app != null && p.StageType == "server")
                            {
                                //Call MSMQ
                                Console.WriteLine("Call MSMQ");
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].exe_path, "", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("EXE Triggered ");
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "OUT") != "Error")
                                    {
                                        Console.WriteLine("File moved local to server ");
                                        if (appdetails[0].inprocessapp != null)
                                            Trigger_MSMQ(p.TransId, p.UserId, "inprocess_apps", "P");
                                        else if (appdetails[0].checkout_app != null)
                                            Trigger_MSMQ(p.TransId, p.UserId, "checkout_apps", "P");
                                        else
                                        {
                                            Console.WriteLine("File Move local to server ");
                                            var checkout_apps_file = "checkout_apps";
                                            if (appdetails[0].process_without_file.ToString() == "1")
                                                checkout_apps_file = "checkout_apps_without_filemove";
                                            lot_tran_info lotinfo = new lot_tran_info();
                                            lotinfo.p_tranid = p.TransId.ToString();
                                            lotinfo.p_userid = p.UserId;
                                            lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                            lotinfo.p_option = "checkout";
                                            lotinfo.p_holdreason = "";
                                            Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        }
                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                            else if (appdetails[0].inprocessapp != null)
                            {
                                //Call MSMQ
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].ipaexepath, "", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("EXE Triggered ");
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "PROCESS") != "Error")
                                    {
                                        Console.WriteLine("File moved local to server ");

                                        if (appdetails[0].checkout_app != null)
                                            Trigger_MSMQ(p.TransId, p.UserId, "checkout_apps", "P");
                                        else
                                        {
                                            Console.WriteLine("File Move local to server ");
                                            var checkout_apps_file = "checkout_apps";
                                            if (appdetails[0].process_without_file.ToString() == "1")
                                                checkout_apps_file = "checkout_apps_without_filemove";
                                            lot_tran_info lotinfo = new lot_tran_info();
                                            lotinfo.p_tranid = p.TransId.ToString();
                                            lotinfo.p_userid = p.UserId;
                                            lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                            lotinfo.p_option = "checkout";
                                            lotinfo.p_holdreason = "";
                                            Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        }
                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                            else if (appdetails[0].checkout_app != null)
                            {
                                //Call MSMQ
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("EXE Triggered");
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "CHECKOUT") != "Error")
                                    {

                                        Console.WriteLine("File Move local to server ");
                                        var checkout_apps_file = "checkout_apps";
                                        if (appdetails[0].process_without_file.ToString() == "1")
                                            checkout_apps_file = "checkout_apps_without_filemove";
                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                            else
                            {
                                //Complete The Process...
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].exe_path, "", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("Exe Trigerred ");
                                if (output != "Error")
                                {
                                    var checkout_apps_file = "checkout_apps";
                                    if (appdetails[0].process_without_file.ToString() == "1")
                                        checkout_apps_file = "checkout_apps_without_filemove";

                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "OUT") != "Error")
                                    {
                                        Console.WriteLine("File Move local to server ");
                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);

                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;

                            }
                        }
                    }
                    else if (p.AppType == "inprocess_apps")
                    {
                        if (appdetails[0].inprocessappwatcher == "True" || appdetails[0].inprocessappwatcher == "true")
                        {
                            var output = Trigger_Watcher(p.TransId, p.UserId, "IN", appdetails[0].ipaexepath, p.Flag, p.AppType);
                        }
                        else
                        {
                            if (appdetails[0].checkout_app != null)
                            {
                                //Call MSMQ
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "PROCESS", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("Exe Trigerred ");
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "CHECKOUT") != "Error")
                                    {
                                        Console.WriteLine("File Move local to server ");
                                        var checkout_apps_file = "checkout_apps";
                                        if (appdetails[0].process_without_file.ToString() == "1")
                                            checkout_apps_file = "checkout_apps_without_filemove";
                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                    }

                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                            else
                            {
                                //Complete The Process...
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].ipaexepath, "PROCESS", p.Flag, p.AppType, p.comment);
                                Console.WriteLine("File Move local to server ");
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "OUT") != "Error")
                                    {
                                        var checkout_apps_file = "checkout_apps";
                                        if (appdetails[0].process_without_file.ToString() == "1")
                                            checkout_apps_file = "checkout_apps_without_filemove";

                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);

                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                        }
                    }
                    else if (p.AppType == "checkout_apps_service_withfile")
                    {

                        Console.WriteLine("LAPS2 App Watcher: AppType-checkout_apps_service_withfile");
                        Console.WriteLine("LAPS2 App Watcher: TransId-" + p.TransId.ToString());

                        if (appdetails[0].coaisservice == 1)
                        {

                            //lot_tran_info lotinfo = new lot_tran_info();
                            //lotinfo.p_tranid = p.TransId.ToString();
                            //lotinfo.p_userid = p.UserId;
                            //lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                            //lotinfo.p_option = "checkout";
                            //lotinfo.p_holdreason = "";
                            //Checkout_transaction(lotinfo, "checkout_stage_withfile", p.Flag);
                            //Console.WriteLine("LAPS2 App Watcher: checkout_apps_service_withfile:Checkout_transaction:lotinfo" + lotinfo.ToString());
                            //Console.WriteLine("LAPS2 App Watcher: checkout_apps_service_withfile:Checkout_transaction:Flag" + p.Flag.ToString());

                            //Checkout_transaction_FileMove_Server_to_Server(p.TransId, json[0].p_tranid, filemove_type, false);



                            #region Code to Call API
                            var data = new { transactionid = p.TransId };
                            var input = JsonConvert.SerializeObject(data);
                            var translist = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", input, "getfeaturedetails");
                            var dt = JArray.Parse(translist.ToString());
                            var obj = JObject.Parse(dt[0].ToString());
                            var checkoutappfeature = JArray.Parse(obj["checkoutappfeature"].ToString());
                            var checkinappfeature = obj["checkinappfeature"].ToString();
                            var inprocessappfeature = obj["inprocessappfeature"].ToString();
                            var serviceurlcheckout = obj["serviceurlcheckout"].ToString();
                            var featureList = CommonRepository.ExecuteSP_ReturnList2("spfeaturemasterselect", input, "getactive");
                            List<featureModel> json = new List<featureModel>();
                            var featurelists = checkoutappfeature.Where(c =>
                        c["active"].ToString() == "1");




                            foreach (var featurelist in featurelists)
                            {

                                var url = serviceurlcheckout + featurelist["mdata"].ToString();
                                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" + p.UserId);
                                Console.WriteLine("LAPS2 App Watcher: TransId" + p.TransId);
                                Console.WriteLine("LAPS2 App Watcher: Batch" + p.Batch);
                                Console.WriteLine("LAPS2 App Watcher: comment" + p.comment);

                                pubflowrequest.AddParameter("application/json", "" +
                                                                            "{ " +
                                                                            "\"PublicationType\":\"" + p.PublicationType + "\"," +
                                                                            "\"PublicationID\":\"" + p.PublicationID + "\","
                                                                            +
                                                                            "\"Batch\":\"" + p.Batch + "\","
                                                                             +
                                                                            "\"UserID\":\"" + p.UserId + "\"," +
                                                                            "\"tranid\":\"" + p.TransId + "\","
                                                                            +
                                                                            "\"ActivityComment\":\"" + p.comment + "\"" +
                                                                            "}", ParameterType.RequestBody);



                                IRestResponse responseResult = client.Execute(pubflowrequest);
                                Console.WriteLine("LAPS2 App Watcher:responseResult" + responseResult.Content.ToString());

                                var logdata = new
                                {
                                    errormessage = "responseResult:Content " + responseResult.Content,
                                    createdby = 0,
                                    controller = "Watcher:LoadFunction:checkout_apps_service_withfile after"
                                };
                                int retval = svrinfo.addlog(logdata, "errorlog");
                            }
                            #endregion
                            var output = Trigger_EXE(p.TransId, p.UserId, "IN", "RequestService.KLI_IOService.kli_ioservice", "CHECKOUT", p.Flag, p.AppType, p.comment);
                            if (output == "Error")
                            {
                                Error = output;
                            }
                        }

                        //Check new concept********************


                    }
                    else if (p.AppType == "checkout_apps")
                    {
                        //Complete The Process...
                        if (appdetails[0].checkout_appwatcher == "True" || appdetails[0].checkout_appwatcher == "true")
                        {
                            var output = Trigger_Watcher(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, p.Flag, p.AppType);
                        }
                        else
                        {
                            Console.WriteLine("LAPS2 App Watcher: checkout_apps:exepath" + appdetails[0].coaexepath);
                            CommonClass.laps2Log("checkout_apps" + p.TransId + "exepath:" + appdetails[0].coaexepath, "Load Function started");
                            if (appdetails[0].checkout_app == CustomConfiguration.AppSettings.GetValue<string>("AppSettings:checkoutappservice"))
                            {
                                var checkout_apps_file = "checkout_apps";
                                if (appdetails[0].process_without_file.ToString() == "1")
                                    checkout_apps_file = "checkout_apps_without_filemove";

                                //Check new concept********************
                                lot_tran_info lotinfo = new lot_tran_info();
                                lotinfo.p_tranid = p.TransId.ToString();
                                lotinfo.p_userid = p.UserId;
                                lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                lotinfo.p_option = "checkout";
                                lotinfo.p_holdreason = "";
                                // Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                if (p.Flag == "R")
                                {
                                    Checkout_transaction(lotinfo, checkout_apps_file, "F");
                                }
                                else
                                {
                                    Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                }

                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "CHECKOUT", p.Flag, p.AppType, p.comment);
                                if (output == "Error")
                                {
                                    Error = output;
                                }
                            }
                            else
                            {
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "CHECKOUT", p.Flag, p.AppType, p.comment);
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "OUT") != "Error")
                                    {
                                        var checkout_apps_file = "checkout_apps";
                                        if (appdetails[0].process_without_file.ToString() == "1")
                                            checkout_apps_file = "checkout_apps_without_filemove";

                                        //Check new concept********************
                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        //if (p.Flag == "R")
                                        //{
                                        //    Checkout_transaction(lotinfo, checkout_apps_file, "F");
                                        //}
                                        //else
                                        //{
                                        //    Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        //}


                                        //*************************************
                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                        }
                    }
                    else if (p.AppType == "checkout_apps_forcmapprove")
                    {
                        //Complete The Process...
                        if (appdetails[0].checkout_appwatcher == "True" || appdetails[0].checkout_appwatcher == "true")
                        {
                            var output = Trigger_Watcher(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, p.Flag, p.AppType);
                        }
                        else
                        {
                            Console.WriteLine("LAPS2 App Watcher: checkout_apps:exepath" + appdetails[0].coaexepath);
                            CommonClass.laps2Log("checkout_apps" + p.TransId + "exepath:" + appdetails[0].coaexepath, "Load Function started");
                            if (appdetails[0].checkout_app == CustomConfiguration.AppSettings.GetValue<string>("AppSettings:checkoutappservice"))
                            {
                                var checkout_apps_file = "checkout_apps";
                                if (appdetails[0].process_without_file.ToString() == "1")
                                    checkout_apps_file = "checkout_apps_without_filemove";

                                //Check new concept********************
                                lot_tran_info lotinfo = new lot_tran_info();
                                lotinfo.p_tranid = p.TransId.ToString();
                                lotinfo.p_userid = p.UserId;
                                lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                lotinfo.p_option = "checkout";
                                lotinfo.p_holdreason = "";
                                // Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "CHECKOUT", p.Flag, p.AppType, p.comment);
                                if (output == "Error")
                                {
                                    Error = output;
                                }
                            }
                            else
                            {
                                var output = Trigger_EXE(p.TransId, p.UserId, "IN", appdetails[0].coaexepath, "CHECKOUT", p.Flag, p.AppType, p.comment);
                                if (output != "Error")
                                {
                                    if (FileMove_LocalTOServer(appdetails[0].process_without_file.ToString(), p.TransId, output, "OUT") != "Error")
                                    {
                                        var checkout_apps_file = "checkout_apps";
                                        if (appdetails[0].process_without_file.ToString() == "1")
                                            checkout_apps_file = "checkout_apps_without_filemove";

                                        //Check new concept********************
                                        lot_tran_info lotinfo = new lot_tran_info();
                                        lotinfo.p_tranid = p.TransId.ToString();
                                        lotinfo.p_userid = p.UserId;
                                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                                        lotinfo.p_option = "checkout";
                                        lotinfo.p_holdreason = "";
                                        //// Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        if (p.Flag == "R")
                                        {
                                            Checkout_transaction(lotinfo, checkout_apps_file, "F");
                                        }
                                        else
                                        {
                                            Checkout_transaction(lotinfo, checkout_apps_file, p.Flag);
                                        }


                                        //*************************************
                                    }
                                    else
                                        Error = "Error";
                                }
                                else
                                    Error = output;
                            }
                        }
                    }
                    else if (p.AppType == "checkout_stage_withfile")
                    {
                        Console.WriteLine("App Details data getting:checkout_stage_withfile");
                        //Check new concept********************
                        lot_tran_info lotinfo = new lot_tran_info();
                        lotinfo.p_tranid = p.TransId.ToString();
                        lotinfo.p_userid = p.UserId;
                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                        lotinfo.p_option = "checkout";
                        lotinfo.p_holdreason = "";
                        Checkout_transaction(lotinfo, "checkout_stage_withfile", p.Flag);
                        //*************************************
                    }
                    else if (p.AppType == "checkout_stage_withoutfile")
                    {
                        lot_tran_info lotinfo = new lot_tran_info();
                        lotinfo.p_tranid = p.TransId.ToString();
                        lotinfo.p_userid = p.UserId;
                        lotinfo.p_jobworkflowid = appdetails[0].jobworkflowid.ToString();
                        lotinfo.p_option = "checkout";
                        lotinfo.p_holdreason = "";
                        Checkout_transaction(lotinfo, "checkout_stage_withoutfile", p.Flag);
                    }
                    if (Error == "Error")
                    {
                        VendorMail.CallErrorMessage(p.TransId, appdetails[0].process_without_file.ToString(), appdetails[0].jobid.ToString(), appdetails[0].lotid.ToString(), "checkout_stage_withoutfile", "LAPS WATCHER : FileMove_ServerTOLocal ERROR", 0, "");

                        CommonClass.WriteLog(fileName, p.TransId, " FileMove_ServerTOLocal ERROR ");
                    }
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("RequestConsumer:LoadFunction:Error" + Ex.Message.ToString());
                var logdata = new
                {
                    errormessage = Ex.Message,
                    createdby = 0,
                    controller = "Watcher:LoadFunction"
                };
                int retval = svrinfo.addlog(logdata, "errorlog");
                CommonClass.ErrorLog(Ex);
                VendorMail.CallErrorMessage(p.TransId, "0", "0", "0", "LAPS WATCHER", Ex.Message.ToString(), 0, "", Ex);

                CommonClass.WriteLog(fileName, p.TransId, Ex.ToString());

            }
        }

        public static async Task<IRestResponse> Trigger_API(string url, RestRequest pubflowrequest)
        {
            IRestResponse responseResult = null;
            try
            {
                Console.WriteLine("LAPS2 App Watcher: Trigger_API:url" + url.ToString());

                var client = new RestClient(url);
                responseResult = await client.ExecuteAsync(pubflowrequest);

                Console.WriteLine("LAPS2 App Watcher: Trigger_API:ResponseStatus: " + responseResult.ResponseStatus.ToString());
                Console.WriteLine("LAPS2 App Watcher: Trigger_API:IsSuccessful: " + responseResult.IsSuccessful.ToString());
                Console.WriteLine("LAPS2 App Watcher: Trigger_API:IsAbsoluteUri: " + responseResult.ResponseUri.IsAbsoluteUri.ToString());
                return responseResult;
            }
            catch (Exception ex)
            {
                Console.WriteLine("LAPS2 App Watcher: Trigger_APIAsync:Error" + ex.Message.ToString());
                return responseResult;
            }

        }
        public static string Trigger_Watcher(string tranid, string userid, string SubDir, string exe_path, string Flag, string appType)
        {
            try
            {
                var exeparam = Build_Params(tranid, userid, System.IO.Path.Combine(Process_Path, tranid), Flag, appType, "");
                CommonClass.ExecCompwatcher(exe_path, exeparam, System.IO.Path.GetDirectoryName(exe_path));
                return "true";
            }
            catch (Exception ex)
            {
                CommonClass.ErrorLog(ex);
                VendorMail.CallErrorMessage(tranid, "0", "0", "0", "LAPS WATCHER", ex.Message.ToString(), 0, "", ex);
                CommonClass.WriteLog(fileName, tranid, ex.ToString());
                return "Error";
            }


        }
        public static string Trigger_EXE(string tranid, string userid, string SubDir, string exe_path, string ProcessCheck, string Flag, string appType, string comment)
        {
            try
            {
                Console.WriteLine("LAPS2 App Watcher: Trigger_EXE" + "tranid" + tranid + "exepath:" + exe_path, "Trigger_EXE started");
                CommonClass.laps2Log("tranid" + tranid + "exepath:" + exe_path, "Trigger_EXE started");
                Type type = Type.GetType(exe_path);

                //if (type != null)
                if (exe_path != null && exe_path != "")
                {
                    //if (File.Exists(exe_path))
                    //{
                    ServerInfo svrinfo = new ServerInfo();
                    string serverpath = svrinfo.GetServerPath(tranid, "serverinfo", true);
                    if (ProcessCheck != "")
                    {
                        if (Directory.Exists(System.IO.Path.Combine(serverpath, ProcessCheck)))
                            SubDir = ProcessCheck;
                        else if (Directory.Exists(System.IO.Path.Combine(serverpath, "PROCESS")))
                            SubDir = "PROCESS";
                    }

                    var exeparam = Build_Params(tranid, userid, "", Flag, appType, comment);
                    //CommonClass.ExecComp(exe_path, exeparam, System.IO.Path.GetDirectoryName(exe_path));
                    CommonClass.ExecCompwatcher(exe_path, exeparam, System.IO.Path.GetDirectoryName(exe_path));
                    return System.IO.Path.Combine(serverpath);
                    ////Files Copy to ServerToLocal
                    //var LocalPath = FileMove_ServerTOServer(tranid, serverpath, SubDir);
                    //if (LocalPath != "Error")
                    //{
                    //    exeparam = Build_Params(tranid, userid, LocalPath, Flag, appType);
                    //    if (!Directory.Exists(System.IO.Path.Combine(LocalPath, "OUT")))
                    //        Directory.CreateDirectory(System.IO.Path.Combine(LocalPath, "OUT"));
                    //    //Call EXE
                    //    CommonClass.ExecComp(exe_path, exeparam, System.IO.Path.GetDirectoryName(exe_path));
                    //    return System.IO.Path.Combine(serverpath);
                    //}
                    //else
                    //{
                    //    //Call Error
                    //    // CheckIn_Checkout(tranid, userid, "makefailed", "D");
                    //    VendorMail.CallErrorMessage(tranid, "0", "0", "0", "LAPS WATCHER", " FileMove_ServerTOLocal ERROR", 0, "");
                    //    CommonClass.WriteLog(fileName, tranid, " FileMove_ServerTOLocal ERROR ");
                    //    return "Error";
                    //}

                }
                else
                {
                    //    //Call Error
                    //CheckIn_Checkout(tranid, userid, "makefailed", "D");
                    VendorMail.CallErrorMessage(tranid, "0", "0", "0", "LAPS WATCHER", " EXE Not in path " + exe_path, 0, "");
                    CommonClass.WriteLog(fileName, tranid, " EXE Not in path " + exe_path);
                    return "Error";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("RequestConsumer:Trigger_EXE:Error" + ex.Message.ToString());
                CommonClass.ErrorLog(ex);
                // CheckIn_Checkout(tranid, userid, "makefailed", "D");
                VendorMail.CallErrorMessage(tranid, "0", "0", "0", "LAPS WATCHER", ex.Message.ToString(), 0, "", ex);
                CommonClass.WriteLog(fileName, tranid, ex.ToString());
                return "Error";
            }


        }
        public static string Build_Params(string tranid, string userid, string LocalPath, string Flag, string appType, string comment)
        {

            //string exeparam = string.Join(" ", "\"" + string.Join(",", tranid, userid, System.IO.Path.Combine(LocalPath, "IN"), System.IO.Path.Combine(LocalPath, "OUT"), Global.Enviroinment, appType, Flag + "\""));
            //return exeparam;
            string exeparam = string.Join(" ", string.Join(",", tranid, userid, System.IO.Path.Combine(LocalPath, "IN"), System.IO.Path.Combine(LocalPath, "OUT"), Global.Enviroinment, appType, Flag, comment));
            return exeparam;
        }
        public static void Trigger_MSMQ(string tranid, string userid, string app_type, string status)
        {
            try
            {
                Console.WriteLine("RequestConsumer:Trigger_MSMQ:tranid: " + tranid + " app_type" + app_type);
                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(userid), direction: ParameterDirection.Input);
                    param.Add("p_status", dbType: DbType.String, value: status, direction: ParameterDirection.Input);
                    param.Add("p_option", dbType: DbType.String, value: app_type, direction: ParameterDirection.Input);
                    var Checkinapp = dbConnection.Query<string>("public.spusrlottranupdatev1", param, commandType: CommandType.StoredProcedure).ToList();

                    //   var Checkinapp = db1.GetDataTable(db, "select * from usr_lot_tran_update_v1(" + tranid + ", " + userid + ", '" + status + "', '" + app_type + "') as dd",
                    //null);
                    if (Checkinapp != null)
                    {
                        // var i_Checkinapp = JsonConvert.DeserializeObject<object>(Checkinapp[0].ToString());
                        // checkinprocess obj = JsonConvert.DeserializeObject<checkinprocess>(Checkinapp[0].ToString());
                        var next_ordernodata10 = JsonConvert.DeserializeObject<object>(Checkinapp[0].ToString());
                        JArray dtparallelnextstage10 = JArray.Parse(next_ordernodata10.ToString());

                        checkinprocess obj = JsonConvert.DeserializeObject<checkinprocess>(dtparallelnextstage10[0]["json_build_object"].ToString());
                        //if (obj.ipaddress != null)
                        // {
                        string ServiceAddress = Global.RabbitMQHost + "" + "/" + CustomConfiguration.AppSettings.GetValue<string>("AppSettings:chechoutqueue");
                        var message = new PublishMessage("", tranid, userid, app_type, obj.stagetype, Global.Enviroinment, null, null);
                        //IRequestClient<ISimpleRequest, ISimpleResponse> client = CreateRequestClient(Global._busControl, obj.ipaddress + "" + "\\" + obj.root_path);
                        //var response = client.Request(new SimpleRequest("", tranid, userid, app_type, obj.stagetype, Global.Enviroinment, null, null));
                        RabbitMq MqRef = new RabbitMq();
                        var task = MqRef.Publish(message, ServiceAddress);
                        WriteLog("Queue processing", tranid, app_type);

                        //}

                    }

                    //   var Checkinapp = db1.GetDataTable(db, "select * from usr_lot_tran_update_v1(" + tranid + ", " + userid + ", '" + status + "', '" + app_type + "') as dd",
                    //null);
                    //if (Checkinapp != null)
                    //{
                    //    var i_appType = JsonConvert.DeserializeObject<object>(Checkinapp.ToString());
                    //    JArray Checkinapplist = JArray.Parse(i_appType.ToString());

                    //    foreach (var item in Checkinapplist)
                    //    {
                    //        checkinprocess obj = JsonConvert.DeserializeObject<checkinprocess>(item[0].ToString());
                    //        if (obj.ipaddress != null)
                    //        {
                    //            string ServiceAddress = Global.RabbitMQHost + "" + "/" + CustomConfiguration.AppSettings.GetValue<string>("AppSettings:chechoutqueue");
                    //            var message = new PublishMessage("", tranid, userid, app_type, obj.stagetype, Global.Enviroinment, null, null);
                    //            //IRequestClient<ISimpleRequest, ISimpleResponse> client = CreateRequestClient(Global._busControl, obj.ipaddress + "" + "\\" + obj.root_path);
                    //            //var response = client.Request(new SimpleRequest("", tranid, userid, app_type, obj.stagetype, Global.Enviroinment, null, null));
                    //            RabbitMq MqRef = new RabbitMq();
                    //            var task = MqRef.Publish(message, ServiceAddress);
                    //            WriteLog("Queue processing", tranid, app_type);
                    //        }
                    //    }
                    //}

                    //    if (Checkinapp.Rows.Count > 0)
                    //{
                    //    for (var item = 0; item <= Checkinapp.Rows.Count - 1; item++)
                    //    {
                    //        checkinprocess obj = JsonConvert.DeserializeObject<checkinprocess>(Checkinapp.Rows[item][0].ToString());
                    //        if (obj.ipaddress != null)
                    //        {


                    //            IRequestClient<ISimpleRequest, ISimpleResponse> client = CreateRequestClient(Global._busControl, obj.ipaddress + "" + "\\" + obj.root_path);
                    //            var response = client.Request(new SimpleRequest("", tranid, userid, app_type, obj.stagetype, Global.Enviroinment, null, null));
                    //            WriteLog("Queue processing", tranid, app_type);

                    //        }
                    //    }
                    //}
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error:" + Ex.Message);
                CommonClass.ErrorLog(Ex);
                //CheckIn_Checkout(tranid, userid, "makefailed", "D");
                VendorMail.CallErrorMessage(tranid, "0", "0", "0", "LAPS WATCHER", Ex.Message.ToString(), 0, "", Ex);
                CommonClass.WriteLog(fileName, tranid, Ex.ToString());
            }
        }

        public static string CheckIn_Checkout(string tranid, string userid, string option, string status)
        {

            string sTranId = "";


            var data = new { p_tranid = tranid, p_userid = userid, p_status = status, p_option = option };
            var jsonstr = JsonConvert.SerializeObject(data);

            var Checkinapp = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

            //var Checkinapp = db1.GetDataTable(db, "select * from usr_lot_tran_update_v1(" + tranid + ", " + userid + ", '" + status + "', '" + option + "') as dd",
            // null);
            if (Checkinapp != null)
            {
                var i_appType = JsonConvert.DeserializeObject<object>(Checkinapp.ToString());
                JArray Checkinapplist = JArray.Parse(i_appType.ToString());
                System.Collections.Generic.List<resultvalue> appdetails1 = new List<resultvalue>();
                foreach (var item in Checkinapplist)
                {
                    var obj = JsonConvert.DeserializeObject<resultvalue>(item[0].ToString());
                    appdetails1.Add(new resultvalue()
                    {
                        p_tranid = obj.p_tranid
                    });
                }
                if (appdetails1.Count > 0)
                {
                    ServerInfo svrinfo = new ServerInfo();
                    string serverpath = svrinfo.GetServerPath(appdetails1[0].p_tranid, "serverinfo", true);
                    FileMove_LocalTOServer("0", tranid, serverpath, "IN");
                    sTranId = appdetails1[0].p_tranid;
                    //isParallelProcess(tranid,userid);
                }
            }
            //        if (Checkinapp.Rows.Count > 0 && status != "D")
            //{
            //    System.Collections.Generic.List<resultvalue> appdetails1 = new List<resultvalue>();
            //    for (var item = 0; item <= Checkinapp.Rows.Count - 1; item++)
            //    {
            //        var obj = JsonConvert.DeserializeObject<resultvalue>(Checkinapp.Rows[item][0].ToString());
            //        appdetails1.Add(new resultvalue()
            //        {
            //            p_tranid = obj.p_tranid
            //        });
            //    }
            //    if (appdetails1.Count > 0)
            //    {
            //        ServerInfo svrinfo = new ServerInfo();
            //        string serverpath = svrinfo.GetServerPath(appdetails1[0].p_tranid, true, "serverinfo");
            //        FileMove_LocalTOServer("0", tranid, serverpath, "IN");
            //        sTranId = appdetails1[0].p_tranid;
            //        //isParallelProcess(tranid,userid);
            //    }
            //}

            return sTranId;
        }
        public static string CheckIn(string tranid, string userid, string option, string status)
        {

            string sTranId = "";


            var data = new { p_tranid = tranid, p_userid = userid, p_status = status, p_option = option };
            var jsonstr = JsonConvert.SerializeObject(data);

            var Checkinapp = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);
            //var Checkinapp = db1.GetDataTable(db, "select * from usr_lot_tran_update_v1(" + tranid + ", " + userid + ", '" + status + "', '" + option + "') as dd",
            // null);

            return sTranId;
        }
        public static string FileMove_ServerTOLocal(string tranid, string serverpath, string SubDir)
        {
            CommonClass.laps2Log("tranid:" + tranid + "serverpath:" + serverpath, "FileMove_ServerTOLocal started");
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows)
            {
                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                {
                    if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                    {
                        Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                    }
                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, "OUT"), System.IO.Path.Combine(Process_Path, tranid, "IN"));
                        return System.IO.Path.Combine(Process_Path, tranid);
                    }
                    Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(Process_Path, tranid, "IN"));
                        return System.IO.Path.Combine(Process_Path, tranid);
                    }
                    else
                    {
                        CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOLocal File Not Found");
                        return "Error";
                    }
                }
            }
            else
            {
                if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                {
                    Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                }
                int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, "OUT"), "*.*").Length;
                if (Inflecnt != 0)
                {
                    CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, "OUT"), System.IO.Path.Combine(Process_Path, tranid, "IN"));
                    return System.IO.Path.Combine(Process_Path, tranid);
                }
                Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                if (Inflecnt != 0)
                {
                    CommonClass.CopyDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(Process_Path, tranid, "IN"));
                    return System.IO.Path.Combine(Process_Path, tranid);
                }
                else
                {
                    CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOLocal File Not Found");
                    return "Error";
                }
            }

        }
        public static string FileMove_LocalTOServer(string process_without_file, string tranid, string serverpath, string SubDir, string StageType = "", bool isTakeFileBackup = true)
        {
            CommonClass.laps2Log("tranid:" + tranid + "serverpath:" + serverpath, "FileMove_LocalTOServer started");
            if (process_without_file == "1")
                return "Without File Move";
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows)
            {
                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                {
                    if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                    {
                        Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                    }
                    //Backup folder
                    var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(serverpath, "V001"));
                    if (StageType != "checkout_next_merged")
                    {
                        if (isTakeFileBackup == true)
                        {
                            int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                            if (Inflecnt_Backup != 0)
                            {

                                CommonClass.MoveDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                            }
                        }
                    }
                    if (Directory.Exists(System.IO.Path.Combine(Process_Path, tranid, "OUT")))
                    {
                        int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(Process_Path, tranid, "OUT"), "*.*").Length;
                        if (Inflecnt != 0)
                        {
                            CommonClass.CopyDirectory(System.IO.Path.Combine(Process_Path, tranid, "OUT"), System.IO.Path.Combine(serverpath, SubDir));

                            return System.IO.Path.Combine(serverpath, SubDir);
                        }
                        else
                        {
                            CommonClass.WriteLog(fileName, tranid, "FileMove_LocalTOServer File Not Fount");
                            return "Error";
                        }
                    }
                    else
                    {
                        CommonClass.WriteLog(fileName, tranid, "File path not exists");
                        return "";
                    }
                }
            }
            else
            {
                if (!Directory.Exists(System.IO.Path.Combine(serverpath, SubDir)))
                {
                    Directory.CreateDirectory(System.IO.Path.Combine(serverpath, SubDir));
                }
                //Backup folder
                var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(serverpath, "V001"));
                if (StageType != "checkout_next_merged")
                {
                    if (isTakeFileBackup == true)
                    {
                        int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(serverpath, SubDir), "*.*").Length;
                        if (Inflecnt_Backup != 0)
                        {
                            CommonClass.MoveDirectory(System.IO.Path.Combine(serverpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                        }
                    }
                }
                if (Directory.Exists(System.IO.Path.Combine(Process_Path, tranid, "OUT")))
                {
                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(Process_Path, tranid, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {
                        CommonClass.CopyDirectory(System.IO.Path.Combine(Process_Path, tranid, "OUT"), System.IO.Path.Combine(serverpath, SubDir));
                        return System.IO.Path.Combine(serverpath, SubDir);
                    }
                    else
                    {
                        CommonClass.WriteLog(fileName, tranid, "FileMove_LocalTOServer File Not Fount");
                        return "Error";
                    }
                }
                else
                {
                    CommonClass.WriteLog(fileName, tranid, "File path not exists");
                    return "";
                }
            }

        }

        public static string FileMove_ServerTOServer(string tranid, string inputpath, string outputpath, string StageType = "", bool isTakeFileBackup = true)
        {
            Console.WriteLine("RequestConsumer:FileMove_ServerTOServer");
            Console.WriteLine("RequestConsumer:FileMove_ServerTOServer" + "tranid:" + tranid + "inputpath:" + inputpath, "FileMove_ServerTOServer started");

            CommonClass.laps2Log("tranid:" + tranid + "inputpath:" + inputpath, "FileMove_ServerTOServer started");
            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows)
            {
                using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(tranid))
                {
                    var SubDir = "IN";
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                    if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                        Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                    //Backup folder
                    var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                    if (StageType != "checkout_next_merged")
                    {
                        if (isTakeFileBackup == true)
                        {
                            int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                            if (Inflecnt_Backup != 0)
                            {

                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                                CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                            }
                        }
                    }

                    int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                    if (Inflecnt != 0)
                    {

                        CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                        return System.IO.Path.Combine(outputpath, SubDir);
                    }
                    else
                    {
                        if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                            Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                        int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                        if (Inflecnt_ != 0)
                        {

                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                            if (Inflecnt__ != 0)
                            {

                                CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                                return System.IO.Path.Combine(outputpath, SubDir);
                            }
                            else
                            {
                                CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                                return "Error";
                            }
                        }
                    }
                }
            }
            else
            {
                var SubDir = "IN";
                if (!Directory.Exists(System.IO.Path.Combine(outputpath, SubDir)))
                    Directory.CreateDirectory(System.IO.Path.Combine(outputpath, SubDir));
                if (!Directory.Exists(System.IO.Path.Combine(outputpath, "OUT")))
                    Directory.CreateDirectory(System.IO.Path.Combine(outputpath, "OUT"));
                //Backup folder
                var backupDir = CommonClass.GetBackupfolder(System.IO.Path.Combine(outputpath, "V001"));
                if (StageType != "checkout_next_merged")
                {
                    if (isTakeFileBackup == true)
                    {
                        int Inflecnt_Backup = System.IO.Directory.GetFiles(System.IO.Path.Combine(outputpath, SubDir), "*.*").Length;
                        if (Inflecnt_Backup != 0)
                        {

                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, SubDir), System.IO.Path.Combine(backupDir, SubDir));
                            CommonClass.MoveDirectory(System.IO.Path.Combine(outputpath, "OUT"), System.IO.Path.Combine(backupDir, "OUT"));
                        }
                    }
                }

                int Inflecnt = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "OUT"), "*.*").Length;
                if (Inflecnt != 0)
                {

                    CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "OUT"), System.IO.Path.Combine(outputpath, SubDir));
                    return System.IO.Path.Combine(outputpath, SubDir);
                }
                else
                {
                    if (!Directory.Exists(System.IO.Path.Combine(inputpath, "PROCESS")))
                        Directory.CreateDirectory(System.IO.Path.Combine(inputpath, "PROCESS"));
                    int Inflecnt_ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "PROCESS"), "*.*").Length;
                    if (Inflecnt_ != 0)
                    {

                        CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "PROCESS"), System.IO.Path.Combine(outputpath, SubDir));
                        return System.IO.Path.Combine(outputpath, SubDir);
                    }
                    else
                    {
                        int Inflecnt__ = System.IO.Directory.GetFiles(System.IO.Path.Combine(inputpath, "IN"), "*.*").Length;
                        if (Inflecnt__ != 0)
                        {

                            CommonClass.CopyDirectory(System.IO.Path.Combine(inputpath, "IN"), System.IO.Path.Combine(outputpath, SubDir));
                            return System.IO.Path.Combine(outputpath, SubDir);
                        }
                        else
                        {
                            CommonClass.WriteLog(fileName, tranid, "FileMove_ServerTOServer File Not Fount");
                            return "Error";
                        }
                    }
                }
            }

        }
        public static void checkNextStage_MSMQ(string TransId, string userid)
        {

            List<appdetails> appdetails = new List<appdetails>();
            appdetails = CommonClass.CheckAppType(TransId, userid);
            if (appdetails.Count > 0)
            {
                if (appdetails[0].stagetype == "server")
                {
                    Console.WriteLine("checkNextStage_MSMQ:TransId" + TransId);
                    Console.WriteLine("checkNextStage_MSMQ:inprocess_apps" + appdetails[0].inprocessapp);
                    Console.WriteLine("checkNextStage_MSMQ:checkin_app" + appdetails[0].checkin_app);
                    Console.WriteLine("checkNextStage_MSMQ:checkout_app" + appdetails[0].checkout_app);
                    if (appdetails[0].checkin_app != null)
                        Trigger_MSMQ(TransId, userid, "checkin_apps", "P");
                    else if (appdetails[0].inprocessapp != null)
                        Trigger_MSMQ(TransId, userid, "inprocess_apps", "P");
                    else if (appdetails[0].checkout_app != null)
                        Trigger_MSMQ(TransId, userid, "checkout_apps", "P");


                }
                //Application (Web Application) checkin exe triggered...
                else if (appdetails[0].is_checkin_exe == "checkin_exe" && appdetails[0].exe_path != "")
                {
                    //**** Call Checkin EXE(Must watcher only deployed) for Application (not a server process)*******************
                    //**** Tranid status changed to "W".
                    //**** after Watcher triggered to update the status of "R".

                    insertcomments oInsertComments = new insertcomments();
                    oInsertComments.transid = Convert.ToUInt32(TransId);
                    oInsertComments.lotstatus = "W";
                    oInsertComments.p_option = "updatelotstatus";
                    var input = JsonConvert.SerializeObject(oInsertComments);
                    CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

                    //BLDatamanipulation db1 = new BLDatamanipulation();
                    //DBContext db = new DBContext();
                    //string sqry = string.Format("update lot_transaction set lotstatus='@@status' where transactionid = {0}", TransId);
                    //db1.InsertQuery(db, sqry.Replace("@@status", "W"), null);


                    var output = Trigger_Watcher(TransId, userid, "IN", appdetails[0].exe_path, "checkin_apps", "checkin_apps");

                    oInsertComments = new insertcomments();
                    oInsertComments.transid = Convert.ToUInt32(TransId);
                    oInsertComments.lotstatus = "R";
                    oInsertComments.p_option = "updatelotstatus";
                    input = JsonConvert.SerializeObject(oInsertComments);
                    CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

                    //db1.InsertQuery(db, sqry.Replace("@@status", "R"), null);

                }

            }
        }
        public static object Checkout_transaction(lot_tran_info lotinfo, string filemove, string cflag)
        {
            //if Correction "B" comming.....
            //If Correction enabled -- Complete "F" comming......
            Console.WriteLine("coming to Checkout_transaction");
            var trans_id = lotinfo.p_tranid;
            if (string.IsNullOrEmpty(cflag))
                cflag = string.Empty;

            //var checkout = getCheckout(trans_id, lotinfo.p_userid, (cflag.Equals("G") ? "G" : "C"), (cflag.Equals("G") ? "ignore" : "checkout_only"), lotinfo.p_jobworkflowid, lotinfo.p_holdreason);
            var checkout = new List<jsonvalue>();
            if (cflag == "B")
            {
                checkout = getCheckout(trans_id, lotinfo.p_userid, cflag, "ignore", lotinfo.p_jobworkflowid, lotinfo.p_holdreason);
            }
            else
            {
                Console.WriteLine("coming to else of B flag");
                checkout = getCheckout(trans_id, lotinfo.p_userid, (cflag.Equals("G") ? "G" : "C"), (cflag.Equals("G") ? "ignore" : "checkout_only"), lotinfo.p_jobworkflowid, lotinfo.p_holdreason);
            }
            var qtransdata = new { transactionid = trans_id };
            var queryjsonstr = JsonConvert.SerializeObject(qtransdata);
            var returnres = CommonRepository.ExecuteSP_ReturnList2("splottransactionselect", queryjsonstr, "getqueryraiseddetailsbytranid");
            if (returnres != null)
            {

                var qdt = JsonConvert.DeserializeObject<object>(returnres.ToString());
                JArray qobjlotrans = JArray.Parse(qdt.ToString());
                JObject obj1 = JObject.Parse(qobjlotrans[0].ToString());
                if (obj1["queryraised"].ToString().Trim() == "True") // if query is present 
                {
                    int currentstageorder = Convert.ToInt32(obj1["stageorder"].ToString());
                    int nexrstageorder = Convert.ToInt32(obj1["nextstageorder"].ToString());
                    Checkout_next(trans_id, lotinfo.p_userid, obj1["jobworkflowid"].ToString(), obj1["nextjobworkflowid"].ToString(), lotinfo.p_holdreason, filemove, lotinfo, "R");
                }
                else // if no query is present 
                {
                    Console.WriteLine("no query present");
                    if (checkout.Count > 0)
                    {
                        foreach (var item in checkout)
                        {
                            var next_ordernodata10 = JsonConvert.DeserializeObject<object>(item.json);
                            JArray dtparallelnextstage10 = JArray.Parse(next_ordernodata10.ToString());

                            JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(dtparallelnextstage10[0].ToString());
                            List<StageData> lst = new List<StageData>();

                            //******************* Get Next Stage Details **************
                            lst = getNextStageDetails(obj.jobid);
                            //lst = getNextStageDetails(obj.jobid, obj.jobworkflowid);
                            //*******************

                            List<StageData> newList = lst
                             .Where(m => m.CURRENT == obj.jobworkflowid)
                             .ToList();

                            //**********Code to check the parallel decision is occur *******

                            // DataTable dtparallelnextstage = db1.GetDataTable(db, "select a.jobworkflowid as json from parallel_decision_making a where a.tranid = " + trans_id + " and active=1", null);


                            var data = new { tranid = trans_id };
                            var jsonstr = JsonConvert.SerializeObject(data);
                            var next_ordernores = CommonRepository.ExecuteSP_ReturnList2("spparalleldecisionmakingselect", jsonstr, "getbytranid");
                            JArray dtparallelnextstage = new JArray();
                            if (next_ordernores != null)
                            {
                                var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());

                                //  var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());
                                dtparallelnextstage = JArray.Parse(next_ordernodata.ToString());
                            }



                            List<string> listparallelnextstage = new List<string>();
                            foreach (var dr in dtparallelnextstage)
                            {
                                listparallelnextstage.Add(dr[0].ToString());
                            }
                            List<StageData> newListparallel = newList.Where(p => listparallelnextstage.Any(p2 => p2 == p.PARALLEL || p2 == p.NEXT)).ToList();
                            if (newListparallel.Count > 0)
                                newList = newListparallel;
                            //**************

                            //******************* To Check Next Stage 
                            foreach (var items in newList)
                            {
                                var next_workflow_id = "";
                                //Correction Back
                                if (cflag == "B")
                                {
                                    if (items.MOVEBACKYES != null)
                                    {
                                        next_workflow_id = items.MOVEBACKYES;
                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");

                                        var trandata = new { p_tranid = trans_id };
                                        var transresult = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updatedocrejected", "Üpdate lottrans");

                                        // DataTable dt = db1.GetDataTable(db, "select a.stageorder from job_workflow_master a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid and  b.jobworkflowid = " + next_workflow_id + " left outer join job_workflow_master c on a.jobworkflowid = c.jobworkflowid and  c.jobworkflowid = " + obj.jobworkflowid.ToString() + " where b.jobworkflowid = " + next_workflow_id + " or  c.jobworkflowid = " + obj.jobworkflowid.ToString() + " order by a.stageorder", null);


                                        var data1 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                        var jsonstr1 = JsonConvert.SerializeObject(data1);
                                        var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr1, "getbyjobworkflowid1");


                                        var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                                        JArray dt = JArray.Parse(next_ordernodata1.ToString());

                                        if (dt.Count > 1)
                                        {
                                            // DataTable dt_order = db1.GetDataTable(db, "select stageorder,jobworkflowid from job_workflow_master a where a.jobworkflowid = " + obj.jobworkflowid.ToString() + " union all select stageorder,jobworkflowid from job_workflow_master a where a.jobworkflowid = " + next_workflow_id + "", null);

                                            var data2 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                            var jsonstr2 = JsonConvert.SerializeObject(data2);
                                            var next_ordernores2 = CommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr2, "getbyjobworkflowid1");
                                            var next_ordernodata2 = JsonConvert.DeserializeObject<object>(next_ordernores2.ToString());
                                            JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

                                            if (dt_order.Count > 1)
                                            {
                                                if (Convert.ToInt32(dt_order[0][0].ToString()) > Convert.ToInt32(dt_order[1][0].ToString()))
                                                {
                                                    //Backward
                                                    var data3 = new { tranid = trans_id, fromorder = dt[1][0].ToString(), toorder = dt[0][0].ToString(), option = 'B' };
                                                    var data31 = CommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data3, null, "jobBackForward");

                                                    //DataTable data31 = db1.GetDataTable(db, "select * from job_back_forwad(" + trans_id + "," + dt.Rows[1][0].ToString() + "," + dt.Rows[0][0].ToString() + ",'B') as json", null);
                                                }
                                                if (Convert.ToInt32(dt_order[0][0].ToString()) < Convert.ToInt32(dt_order[1][0].ToString()))
                                                {
                                                    //Forward
                                                    var data4 = new { tranid = trans_id, fromorder = dt[0][0].ToString(), toorder = dt[1][0].ToString(), option = 'F' };
                                                    var data31 = CommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data4, null, "jobBackForward");
                                                    //DataTable data31 = db1.GetDataTable(db, "select * from job_back_forwad(" + trans_id + "," + dt.Rows[0][0].ToString() + "," + dt.Rows[1][0].ToString() + ",'F') as json", null);
                                                }
                                            }
                                        }
                                    }
                                }
                                //Correction Next
                                else if (cflag == "F")
                                {
                                    if (items.MOVEBACKNO != null)
                                    {
                                        next_workflow_id = items.MOVEBACKNO;
                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");

                                    }
                                }
                                else if (cflag == "G")
                                {

                                    if (items.MOVEBACKNO != null)
                                    {
                                        next_workflow_id = items.MOVEBACKNO;
                                        Console.WriteLine("came to moveback not null");
                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "G");
                                    }
                                    else if (items.NEXT != null)
                                    {
                                        next_workflow_id = items.NEXT;
                                        Console.WriteLine("came to next not null");
                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "G");
                                    }
                                }
                                else
                                {
                                    if (items.NEXT != null)
                                        next_workflow_id = items.NEXT;
                                    else if (items.PARALLEL != null)
                                        next_workflow_id = items.PARALLEL;

                                    //*******************
                                    if (next_workflow_id != null)
                                    {
                                        next_workflow_id = next_workflow_id.Trim();
                                        List<StageData> checkParallalList = lst
                                               .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id)
                                               .ToList();

                                        List<StageData> checkParallalList_Duplicate = new List<StageData>();
                                        if (checkParallalList.Count > 0)
                                        {
                                            var if_check_parallel = true;
                                            //***************** Only One Next Stage
                                            if (checkParallalList.Count == 1)
                                            {
                                                Console.WriteLine("came to first checkParallalList");
                                                Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");
                                            }
                                            //***************** More than One Next Stage
                                            else
                                            {
                                                ////***************** To check Move back is availabale
                                                checkParallalList_Duplicate = checkParallalList;
                                                try
                                                {
                                                    foreach (var item_checkParallalList in checkParallalList)
                                                    {
                                                        var data3 = new { jobworkflowid = item_checkParallalList.NEXT };
                                                        var jsonstr3 = JsonConvert.SerializeObject(data3);
                                                        var next_ordernores3 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr3, "getstageorder");
                                                        var next_ordernodata3 = JsonConvert.DeserializeObject<object>(next_ordernores3.ToString());
                                                        JArray next_orderno3 = JArray.Parse(next_ordernodata3.ToString());
                                                        //var next_orderno = db1.GetDataTable(db, "select stageorder from job_workflow_master a where a.jobworkflowid = " + item_checkParallalList.NEXT + "", null);

                                                        var data4 = new { jobworkflowid = item_checkParallalList.CURRENT };
                                                        var jsonstr4 = JsonConvert.SerializeObject(data4);
                                                        var current_ordernores4 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr4, "getstageorder");
                                                        var current_ordernodata4 = JsonConvert.DeserializeObject<object>(current_ordernores4.ToString());
                                                        JArray current_orderno4 = JArray.Parse(current_ordernodata4.ToString());

                                                        //var current_orderno = db1.GetDataTable(db, "select stageorder from job_workflow_master a where a.jobworkflowid = " + item_checkParallalList.CURRENT + "", null);

                                                        if (Convert.ToInt32(next_orderno3[0]["stageorder"]) < Convert.ToInt32(current_orderno4[0]["stageorder"]))
                                                        {
                                                            checkParallalList_Duplicate.RemoveAll(x => x.CURRENT == item_checkParallalList.CURRENT);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine(ex.Message.ToString());
                                                }
                                                checkParallalList = checkParallalList_Duplicate;
                                                ////***************** More than One Next Stage but moveback yes or no available . do not use parallel completion


                                                if (checkParallalList.Count == 1)
                                                {
                                                    Console.WriteLine("came to checkParallalList");
                                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");
                                                }
                                                else
                                                {
                                                    foreach (var item_checkParallalList in checkParallalList)
                                                    {
                                                        //***************** To Check All Parallal stage are completed or put Wait
                                                        var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT);
                                                        if (checkout_check_parallel.Count > 0)
                                                        {
                                                            foreach (var parallel_item in checkout_check_parallel)
                                                            {
                                                                // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);


                                                                var next_ordernodata11 = JsonConvert.DeserializeObject<object>(parallel_item.json);
                                                                JArray dtparallelnextstage11 = JArray.Parse(next_ordernodata11.ToString());

                                                                JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(dtparallelnextstage11[0]["json"].ToString());


                                                                if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
                                                                {
                                                                    if_check_parallel = false;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if (if_check_parallel == true)
                                                    {
                                                        Console.WriteLine("came if_check_parallel == true");
                                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R", false);
                                                    }
                                                    else
                                                    {
                                                        Console.WriteLine("came else of if_check_parallel == true");
                                                        Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "W", false);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                //*******************
                            }
                        }
                    }
                }
            }
            else // if no query is present 
            {

                if (checkout.Count > 0)
                {
                    foreach (var item in checkout)
                    {
                        var next_ordernodata10 = JsonConvert.DeserializeObject<object>(item.json);
                        JArray dtparallelnextstage10 = JArray.Parse(next_ordernodata10.ToString());

                        JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(dtparallelnextstage10[0].ToString());
                        List<StageData> lst = new List<StageData>();

                        //******************* Get Next Stage Details **************
                        lst = getNextStageDetails(obj.jobid);
                        //lst = getNextStageDetails(obj.jobid, obj.jobworkflowid);
                        //*******************

                        List<StageData> newList = lst
                         .Where(m => m.CURRENT == obj.jobworkflowid)
                         .ToList();

                        //**********Code to check the parallel decision is occur *******

                        // DataTable dtparallelnextstage = db1.GetDataTable(db, "select a.jobworkflowid as json from parallel_decision_making a where a.tranid = " + trans_id + " and active=1", null);


                        var data = new { tranid = trans_id };
                        var jsonstr = JsonConvert.SerializeObject(data);
                        var next_ordernores = CommonRepository.ExecuteSP_ReturnList2("spparalleldecisionmakingselect", jsonstr, "getbytranid");
                        JArray dtparallelnextstage = new JArray();
                        if (next_ordernores != null)
                        {
                            var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());

                            //  var next_ordernodata = JsonConvert.DeserializeObject<object>(next_ordernores.ToString());
                            dtparallelnextstage = JArray.Parse(next_ordernodata.ToString());
                        }



                        List<string> listparallelnextstage = new List<string>();
                        foreach (var dr in dtparallelnextstage)
                        {
                            listparallelnextstage.Add(dr[0].ToString());
                        }
                        List<StageData> newListparallel = newList.Where(p => listparallelnextstage.Any(p2 => p2 == p.PARALLEL || p2 == p.NEXT)).ToList();
                        if (newListparallel.Count > 0)
                            newList = newListparallel;
                        //**************

                        //******************* To Check Next Stage 
                        foreach (var items in newList)
                        {
                            var next_workflow_id = "";
                            //Correction Back
                            if (cflag == "B")
                            {
                                if (items.MOVEBACKYES != null)
                                {
                                    next_workflow_id = items.MOVEBACKYES;
                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");

                                    var trandata = new { p_tranid = trans_id };
                                    var transresult = CommonRepository.ExecuteSP_ReturnInt("splottransaction", trandata, "updatedocrejected", "Üpdate lottrans");

                                    // DataTable dt = db1.GetDataTable(db, "select a.stageorder from job_workflow_master a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid and  b.jobworkflowid = " + next_workflow_id + " left outer join job_workflow_master c on a.jobworkflowid = c.jobworkflowid and  c.jobworkflowid = " + obj.jobworkflowid.ToString() + " where b.jobworkflowid = " + next_workflow_id + " or  c.jobworkflowid = " + obj.jobworkflowid.ToString() + " order by a.stageorder", null);


                                    var data1 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                    var jsonstr1 = JsonConvert.SerializeObject(data1);
                                    var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr1, "getbyjobworkflowid1");


                                    var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                                    JArray dt = JArray.Parse(next_ordernodata1.ToString());

                                    if (dt.Count > 1)
                                    {
                                        // DataTable dt_order = db1.GetDataTable(db, "select stageorder,jobworkflowid from job_workflow_master a where a.jobworkflowid = " + obj.jobworkflowid.ToString() + " union all select stageorder,jobworkflowid from job_workflow_master a where a.jobworkflowid = " + next_workflow_id + "", null);

                                        var data2 = new { jobworkflowid = next_workflow_id, jobworkflowid2 = obj.jobworkflowid.ToString() };
                                        var jsonstr2 = JsonConvert.SerializeObject(data2);
                                        var next_ordernores2 = CommonRepository.ExecuteSP_ReturnList("spjobworkflowdefinitionselect", jsonstr2, "getbyjobworkflowid1");
                                        var next_ordernodata2 = JsonConvert.DeserializeObject<object>(next_ordernores2.ToString());
                                        JArray dt_order = JArray.Parse(next_ordernodata2.ToString());

                                        if (dt_order.Count > 1)
                                        {
                                            if (Convert.ToInt32(dt_order[0][0].ToString()) > Convert.ToInt32(dt_order[1][0].ToString()))
                                            {
                                                //Backward
                                                var data3 = new { tranid = trans_id, fromorder = dt[1][0].ToString(), toorder = dt[0][0].ToString(), option = 'B' };
                                                var data31 = CommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data3, null, "jobBackForward");

                                                //DataTable data31 = db1.GetDataTable(db, "select * from job_back_forwad(" + trans_id + "," + dt.Rows[1][0].ToString() + "," + dt.Rows[0][0].ToString() + ",'B') as json", null);
                                            }
                                            if (Convert.ToInt32(dt_order[0][0].ToString()) < Convert.ToInt32(dt_order[1][0].ToString()))
                                            {
                                                //Forward
                                                var data4 = new { tranid = trans_id, fromorder = dt[0][0].ToString(), toorder = dt[1][0].ToString(), option = 'F' };
                                                var data31 = CommonRepository.ExecuteSP_ReturnInt("spjobbackforward", data4, null, "jobBackForward");
                                                //DataTable data31 = db1.GetDataTable(db, "select * from job_back_forwad(" + trans_id + "," + dt.Rows[0][0].ToString() + "," + dt.Rows[1][0].ToString() + ",'F') as json", null);
                                            }
                                        }
                                    }
                                }
                            }
                            //Correction Next
                            else if (cflag == "F")
                            {
                                if (items.MOVEBACKNO != null)
                                {
                                    next_workflow_id = items.MOVEBACKNO;
                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");

                                }
                            }
                            else if (cflag == "G")
                            {

                                if (items.MOVEBACKNO != null)
                                {
                                    next_workflow_id = items.MOVEBACKNO;
                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "G");
                                }
                                else if (items.NEXT != null)
                                {
                                    next_workflow_id = items.NEXT;
                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "G");
                                }
                            }
                            else
                            {
                                if (items.NEXT != null)
                                    next_workflow_id = items.NEXT;
                                else if (items.PARALLEL != null)
                                    next_workflow_id = items.PARALLEL;

                                //*******************
                                if (next_workflow_id != null)
                                {
                                    next_workflow_id = next_workflow_id.Trim();
                                    List<StageData> checkParallalList = lst
                                           .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id)
                                           .ToList();

                                    List<StageData> checkParallalList_Duplicate = new List<StageData>();
                                    if (checkParallalList.Count > 0)
                                    {
                                        var if_check_parallel = true;
                                        //***************** Only One Next Stage
                                        if (checkParallalList.Count == 1)
                                        {

                                            Console.WriteLine("came if_check_parallel == true");
                                            Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");
                                        }
                                        //***************** More than One Next Stage
                                        else
                                        {
                                            Console.WriteLine("came else of if_check_parallel == true");
                                            ////***************** To check Move back is availabale
                                            checkParallalList_Duplicate = checkParallalList;
                                            try
                                            {
                                                foreach (var item_checkParallalList in checkParallalList)
                                                {
                                                    var data3 = new { jobworkflowid = item_checkParallalList.NEXT };
                                                    var jsonstr3 = JsonConvert.SerializeObject(data3);
                                                    var next_ordernores3 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr3, "getstageorder");
                                                    var next_ordernodata3 = JsonConvert.DeserializeObject<object>(next_ordernores3.ToString());
                                                    JArray next_orderno3 = JArray.Parse(next_ordernodata3.ToString());
                                                    //var next_orderno = db1.GetDataTable(db, "select stageorder from job_workflow_master a where a.jobworkflowid = " + item_checkParallalList.NEXT + "", null);

                                                    var data4 = new { jobworkflowid = item_checkParallalList.CURRENT };
                                                    var jsonstr4 = JsonConvert.SerializeObject(data4);
                                                    var current_ordernores4 = CommonRepository.ExecuteSP_ReturnList2("spgetlotandstagedetails", jsonstr4, "getstageorder");
                                                    var current_ordernodata4 = JsonConvert.DeserializeObject<object>(current_ordernores4.ToString());
                                                    JArray current_orderno4 = JArray.Parse(current_ordernodata4.ToString());

                                                    //var current_orderno = db1.GetDataTable(db, "select stageorder from job_workflow_master a where a.jobworkflowid = " + item_checkParallalList.CURRENT + "", null);

                                                    if (Convert.ToInt32(next_orderno3[0]["stageorder"]) < Convert.ToInt32(current_orderno4[0]["stageorder"]))
                                                    {
                                                        checkParallalList_Duplicate.RemoveAll(x => x.CURRENT == item_checkParallalList.CURRENT);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine(ex.Message.ToString());
                                            }
                                            checkParallalList = checkParallalList_Duplicate;
                                            ////***************** More than One Next Stage but moveback yes or no available . do not use parallel completion


                                            if (checkParallalList.Count == 1)
                                            {
                                                Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R");
                                            }
                                            else
                                            {
                                                foreach (var item_checkParallalList in checkParallalList)
                                                {
                                                    //***************** To Check All Parallal stage are completed or put Wait
                                                    var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT);
                                                    if (checkout_check_parallel.Count > 0)
                                                    {
                                                        foreach (var parallel_item in checkout_check_parallel)
                                                        {
                                                            // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);


                                                            var next_ordernodata11 = JsonConvert.DeserializeObject<object>(parallel_item.json);
                                                            JArray dtparallelnextstage11 = JArray.Parse(next_ordernodata11.ToString());

                                                            JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(dtparallelnextstage11[0]["json"].ToString());


                                                            if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
                                                            {
                                                                if_check_parallel = false;
                                                            }
                                                        }
                                                    }
                                                }
                                                if (if_check_parallel == true)
                                                {
                                                    Console.WriteLine("came if_check_parallel == true");
                                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "R", false);
                                                }
                                                else
                                                {
                                                    Console.WriteLine("came else of if_check_parallel == true");
                                                    Checkout_next(trans_id, lotinfo.p_userid, obj.jobworkflowid.ToString(), next_workflow_id, lotinfo.p_holdreason, filemove, lotinfo, "W", false);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //*******************
                        }
                    }
                }
            }

            return "Done";
        }
        public static void Checkout_next(string trans_id, string p_userid, string jobworkflowid, string next_workflow_id, string p_holdreason, string filemove, lot_tran_info lotinfo, string status, bool isTakeFileBackup = true)
        {
            List<jsonvalue> checkout_next = null;


            insertcomments oInsertComments = new insertcomments();
            oInsertComments.transid = Convert.ToUInt32(trans_id);
            oInsertComments.p_option = "getcurrentstage";
            var input = JsonConvert.SerializeObject(oInsertComments);
            var CurrentStageres = CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
            oInsertComments = new insertcomments();
            oInsertComments.jobworkflowid = Convert.ToUInt32(next_workflow_id);
            oInsertComments.p_option = "getnextstage";
            input = JsonConvert.SerializeObject(oInsertComments);
            var NextStageres = CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

            //var NextStage = db1.GetDataTable(db, " select merged_lot from job_workflow_master where jobworkflowid = " + next_workflow_id + "", null);


            if (CurrentStageres != null) //if (CurrentStage.Rows.Count > 0)
            {
                var data = JsonConvert.DeserializeObject<object>(CurrentStageres.ToString());
                JArray CurrentStage = JArray.Parse(data.ToString());

                data = JsonConvert.DeserializeObject<object>(NextStageres.ToString());
                JArray NextStage = JArray.Parse(data.ToString());

                var merged_lot_current = CurrentStage[0]["merged_lot"].ToString();
                var merged_lot_next = NextStage[0]["merged_lot"].ToString();

                if (merged_lot_current == "0" && merged_lot_next == "0")
                {
                    checkout_next = getCheckout(trans_id, p_userid, status, "checkout_next", next_workflow_id, p_holdreason);
                    Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next", isTakeFileBackup);
                }
                else if (merged_lot_current == "0" && merged_lot_next == "1")
                {

                    if (status == "G")
                    {
                        Console.WriteLine("Coming to status g in merged_lot_next is 0 G");
                        checkout_next = getCheckout(trans_id, p_userid, status, "checkout_next_merged", next_workflow_id, p_holdreason, CurrentStage[0]["lotid"].ToString());

                        oInsertComments = new insertcomments();
                        oInsertComments.lotid = Convert.ToUInt32(CurrentStage[0]["lotid"].ToString());
                        oInsertComments.p_option = "updatelotbatchdetails";
                        input = JsonConvert.SerializeObject(oInsertComments);
                        CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

                        //string sqry = string.Format("update lot_batch_details set merged=true ,active=false,ignored=true where lotid = {0}", CurrentStage.Rows[0]["lotid"].ToString());
                        //db1.InsertQuery(db, sqry, null);
                    }
                    else
                        Console.WriteLine("Coming to else og status G");
                    if (CurrentStage[0]["stageorder"].ToString() == "4")
                    {
                        Console.WriteLine(CurrentStage[0]["stageorder"].ToString() == "4");
                        checkout_next = getCheckout(trans_id, p_userid, "R", "checkout_next_merged", next_workflow_id, p_holdreason);
                    }
                    else
                    {
                        checkout_next = getCheckout(trans_id, p_userid, "W", "checkout_next_merged", next_workflow_id, p_holdreason);
                    }




                    // var Check_All_lot_come = db1.GetDataTable(db, "select * from check_lot_batch_complete (" + CurrentStage[0]["jobid"].ToString() + "," + "0" + "," + CurrentStage[0]["stageorder"].ToString() + ")", null);


                    var data1 = new { jobid = CurrentStage[0]["jobid"].ToString(), stageorder = CurrentStage[0]["stageorder"].ToString() };
                    var jsonstr1 = JsonConvert.SerializeObject(data1);
                    var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("spchecklotbatchcomplete", jsonstr1, "getbyjobid");
                    var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                    JArray Check_All_lot_come = JArray.Parse(next_ordernodata1.ToString());

                    if (Check_All_lot_come.Count > 0)
                    {
                        var lot_cont = Check_All_lot_come[0]["batch_id"].ToString(); //Check_All_lot_come[0][0].ToString();

                        if (lot_cont == "1")
                        {
                            Console.WriteLine("came to lotcount=1");

                            var json = new List<transout>();
                            foreach (var checkout_next_item in checkout_next)
                            {
                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                json.Add(JsonConvert.DeserializeObject<transout>(aa[0].ToString()));
                                //   json.Add(JsonConvert.DeserializeObject<transout>(aa[0]["json_build_object"].ToString()));
                            }


                            oInsertComments = new insertcomments();
                            oInsertComments.transid = Convert.ToUInt32(json[0].p_tranid);
                            oInsertComments.lotstatus = "R";
                            oInsertComments.p_option = "updatelotstatus";
                            input = JsonConvert.SerializeObject(oInsertComments);
                            CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);

                            //db1.InsertQuery(db, "update lot_transaction set lotstatus = 'R' where transactionid = " + json[0].p_tranid + "", null);

                            oInsertComments = new insertcomments();
                            oInsertComments.jobid = Convert.ToUInt32(CurrentStage[0]["jobid"].ToString());
                            oInsertComments.p_option = "updatelotbatch";
                            input = JsonConvert.SerializeObject(oInsertComments);
                            CommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", input);
                            Console.WriteLine("came to lotcount=1");
                            //db1.InsertQuery(db, "update lot_batch set batchstatus ='R' where jobid = " + CurrentStage.Rows[0]["jobid"].ToString() + " and active = 1  and batchstatus ='W'", null);
                            Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_merged", isTakeFileBackup);


                        }
                        else
                        {
                            Console.WriteLine("came to not lotcount=1");
                            var json = new List<transout>();
                            foreach (var checkout_next_item in checkout_next)
                            {
                                JArray aa = JArray.Parse(checkout_next_item.json.ToString());
                                json.Add(JsonConvert.DeserializeObject<transout>(aa[0].ToString()));
                            }
                            //  json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
                            if (json[0].p_tranid != trans_id && status != "G")
                            {
                                Console.WriteLine(trans_id);
                                Console.WriteLine("came to transactionid and lotstatus !=G");
                                if (CurrentStage[0]["stageorder"].ToString() == "4")
                                {
                                    Console.WriteLine(CurrentStage[0]["stageorder"].ToString() == "4");
                                    Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, "R", checkout_next, "checkout_next_merged", isTakeFileBackup);
                                }

                                Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, "W", checkout_next, "checkout_next_merged", isTakeFileBackup);
                            }
                        }
                    }


                    //W--
                }
                else if (merged_lot_current == "1" && merged_lot_next == "1")
                {
                    // var Check_All_lot_come = db1.GetDataTable(db, "select * from check_lot_batch_complete (" + CurrentStage[0]["jobid"].ToString() + "," + "0" + "," + CurrentStage[0]["stageorder"].ToString() + ")", null);

                    checkout_next = getCheckout(trans_id, p_userid, status, "checkout_next", next_workflow_id, p_holdreason);
                    Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_merged_to_merged", isTakeFileBackup);
                }
                else if (merged_lot_current == "1" && merged_lot_next == "0")
                {

                    // var BatchLotDetails = db1.GetDataTable(db, "select lotid from lot_batch_details where batchid = " + CurrentStage[0]["batchid"].ToString() + " and ignored=false", null);

                    var data1 = new { batchid = CurrentStage[0]["batchid"].ToString() };
                    var jsonstr1 = JsonConvert.SerializeObject(data1);
                    var next_ordernores1 = CommonRepository.ExecuteSP_ReturnList2("splotbatchdetailsselect", jsonstr1, "getbybatchid");
                    //JArray aa = JArray.Parse(next_ordernores1.ToString());
                    var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                    JArray BatchLotDetails = JArray.Parse(next_ordernodata1.ToString());

                    if (BatchLotDetails.Count > 0)
                    {
                        for (var item = 0; item <= BatchLotDetails.Count - 1; item++)
                        {
                            //string qry_get_recount = @"select count(*) from (select *,ROW_NUMBER() OVER(PARTITION BY jobworkflowid,lotid ORDER BY transactionid desc) as duplicate from 
                            //        lot_transaction a where lotid = " + BatchLotDetails[item]["lotid"].ToString() + ") as stemp where duplicate = 1 and lotstatus in ('P','R','I','H') ";


                            var data2 = new { n_lotid = BatchLotDetails[item]["lotid"].ToString(), p_option = "getlottransactioncount" };
                            var jsonstr = JsonConvert.SerializeObject(data2);

                            var Checkinapp = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);
                            var i_appType = JsonConvert.DeserializeObject<object>(Checkinapp.ToString());
                            JArray BatchLotDetails2 = JArray.Parse(i_appType.ToString());


                            // if (Convert.ToInt32(db1.GetDataTable(db, qry_get_recount, null).Rows[0][0].ToString()) == 0)
                            if (Convert.ToInt32(BatchLotDetails2[0]["count"].ToString()) == 0)
                            {
                                checkout_next = getCheckout(trans_id, p_userid, status, "checkout_next_unmerged", next_workflow_id, p_holdreason, BatchLotDetails[item]["lotid"].ToString());
                                Checkout_next_complete(trans_id, p_userid, jobworkflowid.ToString(), next_workflow_id, p_holdreason, filemove, lotinfo, status, checkout_next, "checkout_next_unmerged");
                            }

                        }
                    }
                }
                //InitiateSingalR(lotinfo.p_userid, lotinfo.p_tranid, "");
            }



        }

        public static void Checkout_next_complete(string trans_id, string p_userid, string jobworkflowid, string next_workflow_id, string p_holdreason, string filemove, lot_tran_info lotinfo, string status, List<jsonvalue> checkout_next, string filemove_type, bool isTakeFileBackup = true)
        {
            var json = new List<transout>();

            foreach (var checkout_next_item in checkout_next)
            {
                try
                {
                    var jsonStr = checkout_next_item?.json?.ToString();

                    if (string.IsNullOrWhiteSpace(jsonStr))
                        continue; // Skip if json is null or empty

                    JArray aa = JArray.Parse(jsonStr);

                    if (aa.Count == 0)
                        continue; // Skip if no items

                    var firstItem = aa[0];

                    // Try to extract 'json_build_object' or use the entire first item as fallback
                    var jsonObjectToken = firstItem["json_build_object"] ?? firstItem;

                    if (jsonObjectToken == null || jsonObjectToken.Type == JTokenType.Null)
                        continue; // Still null, skip

                    var nestedJson = jsonObjectToken.ToString();

                    var trans = JsonConvert.DeserializeObject<transout>(nestedJson);

                    if (trans != null)
                    {
                        json.Add(trans);
                    }
                }
                catch (Exception ex)
                {
                    // Log error, optional
                    Console.WriteLine($"Error processing item: {ex.Message}");
                    continue;
                }
            }


            //foreach (var checkout_next_item in checkout_next)
            //{
            //    JArray aa = JArray.Parse(checkout_next_item.json.ToString());
            //    var nestedObject = aa[0]["json_build_object"].ToString();
            //    var trans = JsonConvert.DeserializeObject<transout>(nestedObject);
            //    json.Add(trans);

            //    //json.Add(JsonConvert.DeserializeObject<transout>(aa[0]["json_build_object"].ToString()));
            //    //var next_ordernodata11 = JsonConvert.DeserializeObject<object>(aa[0].ToString());
            //    //var next_ordernodata11 = JsonConvert.DeserializeObject<object>(aa[0]["p_tranid"].ToString());
            //    //JArray dtparallelnextstage10 = JArray.Parse(next_ordernodata11.ToString());
            //    // json.Add(JsonConvert.DeserializeObject<transout>(next_ordernodata11.ToString()));
            //    //json.Add(JsonConvert.DeserializeObject<transout>(next_ordernodata11.ToString()));
            //}
            if (filemove == "checkout_stage_withfile")
                Checkout_transaction_FileMove_Server_to_Server(trans_id, json[0].p_tranid, filemove_type, isTakeFileBackup);//------
            else if (filemove == "checkout_apps")
                Checkout_transaction_FileMove(trans_id, json[0].p_tranid, filemove_type, isTakeFileBackup);//------

            if (status != "W")
            {
                Console.WriteLine("came to lotstatus ==W ");
                sendmail(lotinfo, json[0].p_tranid, jobworkflowid, p_userid);
                checkNextStage_MSMQ(json[0].p_tranid, p_userid);
            }
        }

        public static List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "", string lotid = "0")
        {
            List<jsonvalue> result = new List<jsonvalue>();
            string transactiondata = "";

            int groupSize = int.Parse(CustomConfiguration.AppSettings.GetValue<string>("AppSettings:groupSize"));

            var inp_ = new { transactionid = trans_id };
            var inptjson = JsonConvert.SerializeObject(inp_);

            string jobdet = CommonRepository.ExecuteSP_ReturnList2(
                "spinsert_lottransactionsformultiplelots", inptjson, "getjobdetailsbytransactionid").ToString();
            JArray jobdetails = JArray.Parse(jobdet);
            string workflow = jobdetails[0]["project_subtitle"]?.ToString();

            //string checktxt = CommonRepository.ExecuteSP_ReturnList2(
            //   "spinsert_lottransactionsformultiplelots", inptjson, "checktxtlot").ToString();
            //JObject existstxtObj = JObject.Parse(checktxt);
            //bool txtexists = bool.Parse(existstxtObj["exists"]?.ToString() ?? "false");

            var input = new { jobworkflowid = jobworkflowid };
            var inputjson = JsonConvert.SerializeObject(input);

            string stagenamedetails = CommonRepository.ExecuteSP_ReturnList2(
                "spjobworkflowdefinitionselect", inputjson, "getbyjobworkflowid").ToString();

            JArray jsonArray = JArray.Parse(stagenamedetails);
            string stageNameAlias = jsonArray[0]["stagename_alias"]?.ToString();
            string jobid = jsonArray[0]["jobid"]?.ToString();

            var input_ = new { jobid = jobid };
            var inputjson_ = JsonConvert.SerializeObject(input_);

            string totallots = CommonRepository.ExecuteSP_ReturnList2(
                "spinsert_lottransactionsformultiplelots", inputjson_, "getalllotsfromjobmaster").ToString();

            JArray lotArray = JArray.Parse(totallots);
            int totalLots = 0;

            if (lotArray != null && lotArray.Count > 0 && lotArray[0]["totallots"] != null && int.TryParse(lotArray[0]["totallots"].ToString(), out int parsedTotalLots))
            {
                totalLots = parsedTotalLots;
            }

            if (workflow == "LN_BPM_AI" && stageNameAlias == "XML Review" && option == "checkout_next" && status == "R" && totalLots > (groupSize + 1))
            {
                int? pickedBy = null;
                var obj_ = new { transactionid = trans_id };
                var inputjson1_ = JsonConvert.SerializeObject(obj_);
                string lotidResult = CommonRepository.ExecuteSP_ReturnList2(
    "spinsert_lottransactionsformultiplelots", inputjson1_, "getlotidbytransactionid").ToString();

                JArray lotidArray = JArray.Parse(lotidResult);
                string currentlotid = lotidArray[0]["lotid"]?.ToString() ?? "0";


                string completedcount = CommonRepository.ExecuteSP_ReturnList2(
                    "spinsert_lottransactionsformultiplelots", inputjson1_, "getcompletedlotsforworkflowid").ToString();

                JArray lotcompletedArray = JArray.Parse(completedcount);

                int totalcompletedLots = lotcompletedArray.Count;
                List<int> completedLotIds = lotcompletedArray
     .Select(lot => (int)(lot["lotid"] ?? 0))
     .ToList();

                if (totalcompletedLots > groupSize)
                {
                    //int textlot = 0;
                //    string gettxtlots = CommonRepository.ExecuteSP_ReturnList2(
                //"spinsert_lottransactionsformultiplelots", inputjson_, "gettextlotcount").ToString();

                //    JArray txtlotArray = JArray.Parse(gettxtlots);
                //    if (txtlotArray != null && txtlotArray.Count > 0 && txtlotArray[0]["txtlot_count"] != null && int.TryParse(txtlotArray[0]["txtlot_count"].ToString(), out int parsedtxtlots))
                //    {
                //        textlot = parsedtxtlots;
                //    }

                    int remainingLots = totalLots - totalcompletedLots;
                    var checkInput = new
                    {
                        jobworkflowid = jobworkflowid,
                        transactionid = trans_id
                    };

                    string checkJson = JsonConvert.SerializeObject(checkInput);

                    string checkResult = CommonRepository.ExecuteSP_ReturnList2(
                        "spinsert_lottransactionsformultiplelots", checkJson, "check_lotid_exists_in_group_single").ToString();

                    JObject existsObj = JObject.Parse(checkResult);
                    bool exists = bool.Parse(existsObj["exists"]?.ToString() ?? "false");


                    var checkinput = new { jobworkflowid = jobworkflowid };
                    string checkjson = JsonConvert.SerializeObject(checkinput);

                    var checkresult = CommonRepository.ExecuteSP_ReturnList2(
                        "spinsert_lottransactionsformultiplelots", checkjson, "getgroupedlotids");


                    if (checkresult == null && !exists)
                    {


                        List<int> filteredCompletedLotIds = completedLotIds
                        .Where(id => id != int.Parse(currentlotid))
                        .Take(groupSize)
                        .ToList();


                        var lotGroupInput = new
                        {
                            grouplotid = currentlotid,
                            jobworkflowid = jobworkflowid,
                            createdby = p_userid,
                            lotids = filteredCompletedLotIds
                        };

                        string lotGroupJson = JsonConvert.SerializeObject(lotGroupInput);
                        CommonRepository.ExecuteSP_ReturnList2(
                            "spinsert_lottransactionsformultiplelots", lotGroupJson, "insert_lotgroup");
                        var firstInsertInput = new
                        {
                            jobworkflowid = jobworkflowid,
                            pickedby = pickedBy,
                            lotstatus = status,
                            batchid = "",
                            comments_p = "",
                            lotids = new List<int> { Convert.ToInt32(currentlotid) },
                            createdby = p_userid
                        };

                        string firstInsertJson = JsonConvert.SerializeObject(firstInsertInput);
                        transactiondata = CommonRepository.ExecuteSP_ReturnList2(
                            "spinsert_lottransactionsformultiplelots", firstInsertJson, "insert_lottransactions").ToString();



                    }
                    else if (checkresult != null && !exists)
                    {
                        JArray groupArray = JArray.Parse(checkresult.ToString());

                        List<int> groupedLotIds = groupArray
                            .Select(j => int.Parse(j["lotid"]?.ToString() ?? "0"))
                            .ToList();
                        List<int> filteredCompletedLotIds_ = completedLotIds
    .Where(id => id != int.Parse(currentlotid) && !groupedLotIds.Contains(id))
    .ToList();
                        List<int> filteredCompletedLotIds;

                        if (filteredCompletedLotIds_.Count > groupSize)
                        {
                            filteredCompletedLotIds = completedLotIds
                                .Where(id => id != int.Parse(currentlotid) && !groupedLotIds.Contains(id))
                                .Take(groupSize)
                                .ToList();
                            var lotGroupInput = new
                            {
                                grouplotid = currentlotid,
                                jobworkflowid = jobworkflowid,
                                createdby = p_userid,
                                lotids = filteredCompletedLotIds
                            };

                            string lotGroupJson = JsonConvert.SerializeObject(lotGroupInput);
                            CommonRepository.ExecuteSP_ReturnList2(
                                "spinsert_lottransactionsformultiplelots", lotGroupJson, "insert_lotgroup");
                            var firstInsertInput = new
                            {
                                jobworkflowid = jobworkflowid,
                                pickedby = pickedBy,
                                lotstatus = status,
                                batchid = "",
                                comments_p = "",
                                lotids = new List<int> { Convert.ToInt32(currentlotid) },
                                createdby = p_userid
                            };

                            string firstInsertJson = JsonConvert.SerializeObject(firstInsertInput);
                            transactiondata = CommonRepository.ExecuteSP_ReturnList2(
                                "spinsert_lottransactionsformultiplelots", firstInsertJson, "insert_lottransactions").ToString();

                        }
                        else if (remainingLots <= groupSize)
                        {

                            filteredCompletedLotIds = completedLotIds
                                .Where(id => id != int.Parse(currentlotid) && !groupedLotIds.Contains(id))
                                .ToList();
                            var lotGroupInput = new
                            {
                                grouplotid = currentlotid,
                                jobworkflowid = jobworkflowid,
                                createdby = p_userid,
                                lotids = filteredCompletedLotIds
                            };

                            string lotGroupJson = JsonConvert.SerializeObject(lotGroupInput);
                            CommonRepository.ExecuteSP_ReturnList2(
                                "spinsert_lottransactionsformultiplelots", lotGroupJson, "insert_lotgroup");
                            var firstInsertInput = new
                            {
                                jobworkflowid = jobworkflowid,
                                pickedby = pickedBy,
                                lotstatus = status,
                                batchid = "",
                                comments_p = "",
                                lotids = new List<int> { Convert.ToInt32(currentlotid) },
                                createdby = p_userid
                            };

                            string firstInsertJson = JsonConvert.SerializeObject(firstInsertInput);
                            transactiondata = CommonRepository.ExecuteSP_ReturnList2(
                                "spinsert_lottransactionsformultiplelots", firstInsertJson, "insert_lottransactions").ToString();

                        }
                        else
                        {

                            transactiondata = "[{\"p_lotid\":0,\"p_tranid\":0}]";
                        }




                    }
                    else
                    {
                        transactiondata = "[{\"p_lotid\":0,\"p_tranid\":0}]";
                    }

                }
                else
                {
                    //current tranid should complete but should not create next tranid
                    transactiondata = "[{\"p_lotid\":0,\"p_tranid\":0}]";

                }


                jsonvalue dd = new jsonvalue();
                dd.json = transactiondata;
                result.Add(dd);
                return result;
            }
            else if (workflow == "LN_BPM_AI" && stageNameAlias == "XML Review" && option == "checkout_only" && status == "C" && totalLots > (groupSize + 1) )
            {
                int? pickedBy = null;
                var obj_ = new { transactionid = trans_id };
                var inputjson1_ = JsonConvert.SerializeObject(obj_);
                string lotidgroupResult = CommonRepository.ExecuteSP_ReturnList2(
    "spinsert_lottransactionsformultiplelots", inputjson1_, "checkgroupexistbytranid").ToString();
                JArray lotidgroupArray = JArray.Parse(lotidgroupResult);
                List<int> lotIds = lotidgroupArray
    .Select(item => (int)(item["lotid"] ?? 0))
    .ToList();
                var firstInsertInput = new
                {
                    jobworkflowid = jobworkflowid,
                    pickedby = pickedBy,
                    lotstatus = "R",
                    batchid = "",
                    comments_p = "",
                    lotids = lotIds,
                    createdby = p_userid
                };
                string firstInsertJson = JsonConvert.SerializeObject(firstInsertInput);
                transactiondata = CommonRepository.ExecuteSP_ReturnList2(
                    "spinsert_lottransactionsformultiplelots", firstInsertJson, "insert_lottransactions").ToString();
                JArray transactionArray = JArray.Parse(transactiondata);


                foreach (var item in transactionArray)
                {
                    int ltid = (int)(item["p_lotid"] ?? 0);
                    int trnid = (int)(item["p_tranid"] ?? 0);

                    var dat = new
                    {
                        p_tranid = trnid,
                        p_userid = p_userid,
                        p_status = status,
                        p_option = option,
                        n_jobworkflowid = jobworkflowid,
                        p_comments = p_comments,
                        n_lotid = ltid
                    };

                    string jsnstr = JsonConvert.SerializeObject(dat);

                    var rsult = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsnstr);
                    string filename = lotidgroupArray
    .FirstOrDefault(x => (int)(x["lotid"] ?? 0) == ltid)?["filenames"]?.ToString();
                    if (filename != null && filename != "")
                    {
                        bool rslt = MoveSpecificFile_BetweenTransactions(trans_id, trnid.ToString(), filename, "OUT");
                    }
                    var obj2 = new
                    {
                        transactionid = trnid

                    };
                    int jobwrkflowid = Convert.ToInt32(jobworkflowid) + 1;
                    var nxtInsertInput = new
                    {
                        jobworkflowid = jobwrkflowid,
                        pickedby = pickedBy,
                        lotstatus = "R",
                        batchid = "",
                        comments_p = "",
                        lotids = new List<int> { Convert.ToInt32(ltid) },
                        createdby = p_userid
                    };
                    string nextInsertJson = JsonConvert.SerializeObject(nxtInsertInput);
                    string nexttransactiondata = CommonRepository.ExecuteSP_ReturnList2(
                         "spinsert_lottransactionsformultiplelots", nextInsertJson, "insert_lottransactions").ToString();
                    JArray nxttransactionArray = JArray.Parse(nexttransactiondata);
                    string nxttransactionId = nxttransactionArray.Count > 0
    ? nxttransactionArray[0]["p_tranid"]?.ToString() ?? ""
        : "";
                    if (filename != null && filename != "" && nxttransactionId != "" && nxttransactionId != null)
                    {
                        bool rslt = MoveSpecificFile_BetweenTransactions(trnid.ToString(), nxttransactionId, filename, "IN");
                    }
                    checkNextStage_MSMQ(nxttransactionId, p_userid);



                }
                System.Collections.Generic.List<jsonvalue> appdetails1 = new List<jsonvalue>();
                Console.WriteLine("coming to checkout next");
                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 = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

                Console.WriteLine("RequestConsumer:getCheckout:p_status" + status);
                Console.WriteLine("RequestConsumer:getCheckout:trans_id" + trans_id);
                Console.WriteLine("RequestConsumer:getCheckout:option" + option);
                Console.WriteLine("RequestConsumer:getCheckout:jobworkflowid" + jobworkflowid);
                Console.WriteLine("RequestConsumer:getCheckout:lotid" + lotid);


                jsonvalue dd = new jsonvalue();
                dd.json = Checkinapp.ToString();
                appdetails1.Add(dd);
                Console.WriteLine(appdetails1);
                return appdetails1;
            }

            else
            {

                Console.WriteLine("coming to checkout next");
                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 = CommonRepository.ExecuteSP_ReturnList1("spusrlottranupdatev2", jsonstr);

                Console.WriteLine("RequestConsumer:getCheckout:p_status" + status);
                Console.WriteLine("RequestConsumer:getCheckout:trans_id" + trans_id);
                Console.WriteLine("RequestConsumer:getCheckout:option" + option);
                Console.WriteLine("RequestConsumer:getCheckout:jobworkflowid" + jobworkflowid);
                Console.WriteLine("RequestConsumer:getCheckout:lotid" + lotid);
                //var Checkinapp = db1.GetDataTable(db, "select * from usr_lot_tran_update_v2(" + trans_id + ", " + p_userid + ", '" + status + "', '" + option + "', '" + jobworkflowid + "', '" + p_comments + "'," + lotid + ") as dd",
                //      null);
                System.Collections.Generic.List<jsonvalue> appdetails1 = new List<jsonvalue>();
                jsonvalue dd = new jsonvalue();
                dd.json = Checkinapp.ToString();
                appdetails1.Add(dd);
                Console.WriteLine(appdetails1);
                //        if (Checkinapp.Rows.Count > 0)
                //{
                //    for (var item = 0; item <= Checkinapp.Rows.Count - 1; item++)
                //    {
                //        DataRow row = Checkinapp.Rows[item];
                //        Console.WriteLine(row["dd"]);
                //        jsonvalue dd = new jsonvalue();
                //        dd.json = row["dd"].ToString();
                //        appdetails1.Add(dd);
                //    }
                //}
                return appdetails1;
            }
        }
        public static List<StageData> getNextStageDetails(string jobid)
        {
            List<StageData> lst = new List<StageData>();
            JobWorkflow_ oFieldsmodal = new JobWorkflow_();
            oFieldsmodal.jobid = jobid;
            oFieldsmodal.p_option = "getnextstagedetails";
            var input = JsonConvert.SerializeObject(oFieldsmodal);

            var nextStageDetails = CommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
            var i_stageDetails = JsonConvert.DeserializeObject<object>(nextStageDetails.ToString());
            JArray a_stageDetails = JArray.Parse(i_stageDetails.ToString());
            if (a_stageDetails.Count > 0)
            {
                for (int k = 0; k <= a_stageDetails.Count - 1; k++)
                {
                    var splite = a_stageDetails[k]["flowchart"].ToString().Split(',');
                    if (splite.Length > 0)
                    {
                        var current = "";
                        foreach (string word in splite)
                        {
                            var stemp = ""; StageData st = new StageData();
                            var innersplite = word.ToString().Split(':');
                            for (int j = 0; j <= innersplite.Length; j++)
                            {
                                if (innersplite[0] == "CURRENT")
                                    current = innersplite[1].Trim();
                            }
                            for (int j = 0; j <= innersplite.Length; j++)
                            {
                                st.CURRENT = current;
                                if (innersplite[0] == "CURRENT")
                                    stemp = "CURRENT";
                                else if (innersplite[0] == "NEXT")
                                    st.NEXT = innersplite[1].Trim();
                                else if (innersplite[0] == "PARALLEL")
                                    st.PARALLEL = innersplite[1].Trim();
                                else if (innersplite[0] == "MOVEBACKNO")
                                    st.MOVEBACKNO = innersplite[1].Trim();
                                else if (innersplite[0] == "MOVEBACKYES")
                                    st.MOVEBACKYES = innersplite[1].Trim();
                            }
                            if (stemp != "CURRENT")
                                lst.Add(st);
                        }
                    }
                }
            }
            return lst;
        }

        public static void sendmail(lot_tran_info lotinfo, string nexttranval, string jobworkflowid, string userid = "")
        {
            RabbitMq sendmsg = new RabbitMq();
            sendmsg.SendMqMail(lotinfo.p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userid.ToString());
        }
        public static void Checkout_transaction_FileMove(string tranid, string next_tranid, string filemove_type, bool isTakeFileBackup = true)
        {
            ServerInfo svrinfo = new ServerInfo();
            string serverpath = svrinfo.GetServerPath(next_tranid, "serverinfo", true);
            FileMove_LocalTOServer("0", tranid, serverpath, "IN", filemove_type, isTakeFileBackup);
        }
        public static void Checkout_transaction_FileMove_Server_to_Server(string tranid, string next_tranid, string filemove_type, bool isTakeFileBackup = true)
        {
            string stageNameAlias = string.Empty;
            int totalLots = 0;
            int groupSize = int.Parse(CustomConfiguration.AppSettings.GetValue<string>("AppSettings:groupSize"));
            if (next_tranid != "0")
            {
                var input = new { transactionid = next_tranid };
                var inputjson = JsonConvert.SerializeObject(input);

                string stagenamedetails = CommonRepository.ExecuteSP_ReturnList2(
                    "spinsert_lottransactionsformultiplelots", inputjson, "getstagealiasbytransactionid").ToString();
                JArray stageArray = JArray.Parse(stagenamedetails);


                stageNameAlias = stageArray.FirstOrDefault()?["stagename_alias"]?.ToString() ?? "";
                string jobid = stageArray.FirstOrDefault()?["jobid"]?.ToString() ?? "";

                var input_ = new { jobid = jobid };
                var inputjson_ = JsonConvert.SerializeObject(input_);

                string totallots = CommonRepository.ExecuteSP_ReturnList2(
                    "spinsert_lottransactionsformultiplelots", inputjson_, "getalllotsfromjobmaster").ToString();


                JArray lotArray = JArray.Parse(totallots);

                if (lotArray != null && lotArray.Count > 0 && lotArray[0]["totallots"] != null && int.TryParse(lotArray[0]["totallots"].ToString(), out int parsedTotalLots))
                {
                    totalLots = parsedTotalLots;
                }

            }

            ServerInfo svrinfo = new ServerInfo();
            string inputpath = svrinfo.GetServerPath(tranid, "serverinfo", true);
            string outputpath = svrinfo.GetServerPath(next_tranid, "serverinfo", true);
            if (stageNameAlias == "XML Review" && stageNameAlias != "" && totalLots > (groupSize + 1))
            {
                FileMerge_MultipleToSingle(tranid, inputpath, outputpath, filemove_type, isTakeFileBackup);
            }
            else
            {
                FileMove_ServerTOServer(tranid, inputpath, outputpath, filemove_type, isTakeFileBackup);
            }

        }

        #region SingnalR
        private static void InitiateSingalR(string userid, string transid, string jobid)
        {

            try
            {
                var hubConnection = new HubConnection(CustomConfiguration.AppSettings.GetValue<string>("AppSettings:signalr_path").ToString());
                var hubProxy = hubConnection.CreateHubProxy("KanbanBoard");
                hubConnection.Start().Wait();
                uservalue sd = new uservalue();
                sd.userid = "0";
                sd.transid = transid;
                sd.jobid = jobid;
                hubProxy.Invoke("JoinTask", sd).Wait();
            }
            catch (Exception ex) { Console.WriteLine("SignalR not Initiated due to " + ex.Message.ToString()); }
        }
        #endregion
        public static string FileMerge_MultipleToSingle(string tranid, string inputpath, string outputpath, string StageType = "", bool isTakeFileBackup = true)
        {
            ServerInfo svrinfo = new ServerInfo();
            Console.WriteLine("FileMerge_MultipleToSingle started");
            CommonClass.laps2Log("tranid:" + tranid + ", inputpath:" + inputpath, "FileMerge_MultipleToSingle started");


            var inputObj = new { transactionid = tranid };
            string inputJson = JsonConvert.SerializeObject(inputObj);

            string responseJson = CommonRepository.ExecuteSP_ReturnList2(
                "spinsert_lottransactionsformultiplelots",
                inputJson,
                "getrelatedtransactionidsforgroup"
            ).ToString();

            JArray tranArray = JArray.Parse(responseJson);
            List<string> transactionIds = tranArray.Select(t => t["transactionid"]?.ToString()).Where(id => !string.IsNullOrEmpty(id)).ToList();
            List<(string transactionId, string lotId)> lotTranMap = tranArray
    .Select(t => (
        transactionId: t["transactionid"]?.ToString() ?? "",
        lotId: t["lotid"]?.ToString() ?? ""
    ))
    .Where(pair => !string.IsNullOrEmpty(pair.transactionId) && !string.IsNullOrEmpty(pair.lotId))
    .ToList();


            var SubDir = "IN";
            bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            if (!Directory.Exists(Path.Combine(outputpath, SubDir)))
                Directory.CreateDirectory(Path.Combine(outputpath, SubDir));
            if (!Directory.Exists(Path.Combine(outputpath, "OUT")))
                Directory.CreateDirectory(Path.Combine(outputpath, "OUT"));

            var backupDir = CommonClass.GetBackupfolder(Path.Combine(outputpath, "V001"));
            if (StageType != "checkout_next_merged" && isTakeFileBackup)
            {
                int existingFiles = Directory.GetFiles(Path.Combine(outputpath, SubDir), "*.*").Length;
                if (existingFiles > 0)
                {
                    CommonClass.MoveDirectory(Path.Combine(outputpath, SubDir), Path.Combine(backupDir, SubDir));
                    CommonClass.MoveDirectory(Path.Combine(outputpath, "OUT"), Path.Combine(backupDir, "OUT"));
                }
            }


            Dictionary<string, string> lotIdToFilename = new Dictionary<string, string>();


            foreach (var (tid, lotid) in lotTranMap)
            {
                string inputpath_ = svrinfo.GetServerPath(tid, "serverinfo", true);
                string sourcePath = Path.Combine(inputpath_, "OUT");
                if (Directory.Exists(sourcePath))
                {
                    string[] files = Directory.GetFiles(sourcePath, "*.*");
                    if (files.Length > 0)
                    {
                        foreach (string sourceFile in files)
                        {
                            string fileName = Path.GetFileName(sourceFile);
                            string destFile = Path.Combine(Path.Combine(outputpath, SubDir), fileName);
                            File.Copy(sourceFile, destFile, overwrite: true);
                            if (!lotIdToFilename.ContainsKey(lotid))
                                lotIdToFilename[lotid] = fileName;
                        }
                    }
                }
            }
            foreach (var kvp in lotIdToFilename)
            {
                string lotid = kvp.Key;
                string filename = kvp.Value;

                var updateObj = new
                {
                    lotid = lotid,
                    filenames = filename
                };

                string updateJson = JsonConvert.SerializeObject(updateObj);

                try
                {
                    CommonRepository.ExecuteSP_ReturnList2(
                        "spinsert_lottransactionsformultiplelots",
                        updateJson,
                        "update_group_filenames"
                    );
                    CommonClass.WriteLog("FileMerge_MultipleToSingle", lotid, $"Filename updated: {filename}");
                }
                catch (Exception ex)
                {
                    CommonClass.WriteLog("FileMerge_MultipleToSingle", lotid, "Failed to update filename: " + ex.Message);
                }
            }



            if (Directory.GetFiles(Path.Combine(outputpath, SubDir), "*.*").Length > 0)
                return Path.Combine(outputpath, SubDir);
            else
            {
                CommonClass.WriteLog("FileMerge_MultipleToSingle", tranid, "No files found to merge");
                return "Error";
            }
        }

        public static bool MoveSpecificFile_BetweenTransactions(string fromTranId, string toTranId, string fileName, string option)
        {
            try
            {
                ServerInfo svrinfo = new ServerInfo();
                string destFile = string.Empty;
                string fromPath = svrinfo.GetServerPath(fromTranId, "serverinfo", true);
                string filenamewithoutext = Path.GetFileNameWithoutExtension(fileName);
                string sourceFile = Path.Combine(fromPath, "OUT", filenamewithoutext);
                if (!Directory.Exists(sourceFile))
                {
                    CommonClass.WriteLog("MoveSpecificFile", fromTranId, $"File not found: {sourceFile}");
                    return false;
                }
                string toPath = svrinfo.GetServerPath(toTranId, "serverinfo", true);
                string infol = Path.Combine(toPath, "IN");
                string outfol = Path.Combine(toPath, "OUT");
                if (!Directory.Exists(infol))
                    Directory.CreateDirectory(infol);
                if (!Directory.Exists(outfol))
                    Directory.CreateDirectory(outfol);
                if (option == "OUT")
                {
                    destFile = Path.Combine(outfol, filenamewithoutext);
                    Directory.Move(sourceFile, destFile);
                    //File.Move(sourceFile, destFile, true);
                }
                else if (option == "IN")
                {
                    destFile = Path.Combine(infol, filenamewithoutext);
                    //File.Copy(sourceFile, destFile, overwrite: true);
                    CommonClass.CopyDirectory(sourceFile, destFile);



                }
                // Copy or Move (here using Copy to preserve original)
                //File.Copy(sourceFile, destFile, overwrite: true);
                CommonClass.WriteLog("MoveSpecificFile", toTranId, $"File moved: {fileName} from {fromTranId} to {toTranId}");
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.WriteLog("MoveSpecificFile", $"{fromTranId}->{toTranId}", "Error: " + ex.Message);
                return false;
            }
        }

    }
    public class lot_tran_info
    {
        public string p_tranid { set; get; }
        public string p_userid { set; get; }
        public string p_option { set; get; }
        public string p_XmlName { set; get; }
        public string p_holdreason { set; get; }
        public string basexmlUpdate { set; get; }
        public string stageorder { set; get; }
        public string p_jobworkflowid { set; get; }
    }
    public class DynamicParams
    {
        public string jobworkflowid { get; set; }
        public string nexttranid { get; set; }
    }

    public class jobmetafields
    {
        public string name { get; set; }
        public string type { get; set; }
        public string label { get; set; }
        public string workflowdid { get; set; }
        public string value { get; set; }
        public string status { get; set; }
    }

    class transout
    {
        public string p_tranid { get; set; }
    }
    class transactionout
    {
        public string tranid { get; set; }
        public string jobworkflowid { get; set; }
    }
    public class StageData
    {
        public string CURRENT { set; get; }
        public string NEXT { set; get; }
        public string PARALLEL { set; get; }
        public string MOVEBACKYES { set; get; }
        public string MOVEBACKNO { set; get; }
    }

    public class JobWorkflow_
    {
        public string jobworkflowid { set; get; }
        public string jobid { set; get; }
        public string lotid { set; get; }
        public string batchid { set; get; }
        public string lotstatus { set; get; }
        public string p_option { set; get; }
    }

    public struct uservalue
    {


        public string userid;
        public string transid;
        public string jobid;
    }
}
