//using System.IO.Compression;
using Ionic.Zip;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.WorkArea;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WK_KLI_LAPS_Service.Controllers.Common.Uploader
{
    [EnableCors("CorsPolicy")]
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class UploaderApiController : Controller
    {

        CommonRepository oCommonRepository = new CommonRepository();
        WorkAreaService oWorkAreaService = new WorkAreaService();
        UploaderService oUploaderService = new UploaderService();

        //[AllowAnonymous]
        //[HttpPost("Downloader")]
        //public IActionResult Downloader(dynamic fileData)
        //{

        //    try
        //    {
        //        if (fileData.file != null)
        //        {
        //            var list = oUploaderService.getlotsdetailsbytrankey(fileData.L.ToString());
        //            if (list != null)
        //            {
        //                var i1 = JsonConvert.DeserializeObject<object>(list.ToString());
        //                JArray a1 = JArray.Parse(i1.ToString());
        //                JObject obj1 = JObject.Parse(a1[0].ToString());
        //                string transactionid = obj1["transactionid"].ToString();
        //                string serverpath = oUploaderService.GetServerPath(transactionid, false, "serverinfo");
        //                serverpath = Path.Combine(serverpath, "IN");
        //                int jobworkflowid = Convert.ToInt32(obj1["jobworkflowid"].ToString());
        //                int lotid = Convert.ToInt32(obj1["lotid"].ToString());
        //                var query = oUploaderService.getlotsassignmentlotdetails(jobworkflowid, lotid, Convert.ToInt32(fileData.U.ToString()));
        //                if (obj1["batchid"].ToString() != "")
        //                {
        //                    query = oUploaderService.getlotsassignmentlotdetails(jobworkflowid, Convert.ToInt32(obj1["batchid"].ToString()), Convert.ToInt32(fileData.U.ToString()));
        //                }
        //                if (query != null)
        //                {
        //                    var updateLotStatus = oUploaderService.updatelotstatusbytrankey(fileData.L.ToString(), Convert.ToInt32(fileData.U.ToString()), "P");

        //                }
        //                else
        //                {
        //                    return BadRequest(new { message = "Link is not valid" });
        //                }
        //                string tranid = "";
        //                string jobid = "";
        //                string lottitle_zipfilename = "";
        //                if (obj1["lotid"].ToString() == "")
        //                {
        //                    var stagename = oUploaderService.getstagename(jobworkflowid);
        //                    if (stagename != null)
        //                    {
        //                        var i1_stagename = JsonConvert.DeserializeObject<object>(stagename.ToString());
        //                        JArray a1_stagename = JArray.Parse(i1_stagename.ToString());
        //                        JObject obj1_stagename = JObject.Parse(a1_stagename[0].ToString());
        //                        lottitle_zipfilename = obj1_stagename["stagename_alias"].ToString();
        //                    }
        //                    var list_jobid = oUploaderService.getjobid(Convert.ToInt32(obj1["batchid"].ToString()));
        //                    if (list_jobid != null)
        //                    {
        //                        var i1_jobid = JsonConvert.DeserializeObject<object>(list_jobid.ToString());
        //                        JArray a1_jobid = JArray.Parse(i1_jobid.ToString());
        //                        JObject obj1_jobid = JObject.Parse(a1_jobid[0].ToString());
        //                        jobid = obj1_jobid["jobid"].ToString();

        //                    }
        //                }
        //                else
        //                {
        //                    var title = oUploaderService.getjobtitle(lotid);
        //                    if (title != null)
        //                    {
        //                        var i1_title = JsonConvert.DeserializeObject<object>(title.ToString());
        //                        JArray a1_title = JArray.Parse(i1_title.ToString());
        //                        JObject obj1_title = JObject.Parse(a1_title[0].ToString());
        //                        lottitle_zipfilename = obj1_title["title"].ToString();
        //                    }
        //                    var list_tranid = oUploaderService.gettransactionid(fileData.L.ToString());
        //                    if (list_tranid != null)
        //                    {
        //                        var i1_tranid = JsonConvert.DeserializeObject<object>(list_tranid.ToString());
        //                        JArray a1_tranid = JArray.Parse(i1_tranid.ToString());
        //                        JObject obj1_tranid = JObject.Parse(a1_tranid[0].ToString());
        //                        tranid = obj1_tranid["transactionid"].ToString();

        //                    }
        //                }
        //                lottitle_zipfilename = lottitle_zipfilename + ".zip";
        //                string localpath = ""; //Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") + @"/" + fileData.L.ToString().ToString().Trim() + @"/" + lottitle_zipfilename;
        //                int _transactionid = Convert.ToInt32(fileData.T.ToString());
        //                string filePath_tmp = oCommonRepository.getfilesavelocation(_transactionid);
        //                filePath_tmp = filePath_tmp.Replace("/", "\\");
        //                filePath_tmp = @"\\" + filePath_tmp;
        //                if (filePath_tmp != string.Empty)
        //                {
        //                    var serverPath_tmp = Path.Combine(filePath_tmp, "UploadFiles");
        //                    if (!Directory.Exists(serverPath_tmp))
        //                        Directory.CreateDirectory(serverPath_tmp);
        //                    var serverPath_tranid = Path.Combine(serverPath_tmp, _transactionid.ToString());
        //                    if (!Directory.Exists(serverPath_tranid))
        //                        Directory.CreateDirectory(serverPath_tranid);
        //                    localpath = serverPath_tranid;
        //                }
        //                if (!System.IO.File.Exists(localpath))
        //                {
        //                    string filePath = localpath;//Startup.Configuration.GetValue<string>("AppSettings:serverfilepath");
        //                    filePath = filePath + @"\" + fileData.L.ToString().ToString().Trim();
        //                    if (!Directory.Exists(filePath))
        //                        Directory.CreateDirectory(filePath);
        //                    if (System.IO.File.Exists(Path.Combine(filePath, lottitle_zipfilename)))
        //                        System.IO.File.Delete(Path.Combine(filePath, lottitle_zipfilename));
        //                    try
        //                    {

        //                        var cur_stagename = oUploaderService.getstagename(jobworkflowid);
        //                        string current_stagename = "";
        //                        if (cur_stagename != null)
        //                        {
        //                            var i1_cur_stagename = JsonConvert.DeserializeObject<object>(cur_stagename.ToString());
        //                            JArray a1_cur_stagename = JArray.Parse(i1_cur_stagename.ToString());
        //                            JObject obj1_cur_stagename = JObject.Parse(a1_cur_stagename[0].ToString());
        //                            current_stagename = obj1_cur_stagename["stagename_alias"].ToString();
        //                        }
        //                        if (current_stagename.ToLower() == (Startup.Configuration.GetValue<string>("AppSettings:ce_stage_name").ToString().ToLower()))
        //                        {
        //                            try
        //                            {
        //                                string filesT = System.IO.Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => Path.GetExtension(x.ToString()).ToLower().Contains(".docx")).FirstOrDefault();

        //                                string art_foldername = Startup.Configuration.GetValue<string>("AppSettings:art_foldername").ToString();
        //                                string artpdf_foldername = Startup.Configuration.GetValue<string>("AppSettings:artpdf_foldername").ToString();

        //                                if (!Directory.Exists(Path.Combine(filePath, "Temp")))
        //                                {
        //                                    Directory.CreateDirectory(Path.Combine(filePath, "Temp"));
        //                                }

        //                                if (!string.IsNullOrEmpty(filesT))
        //                                {
        //                                    System.IO.File.Copy(filesT, Path.Combine(filePath, "Temp", Path.GetFileName(filesT)), true);
        //                                }

        //                                if (Directory.Exists(Path.Combine(serverpath, art_foldername))
        //                                    && Directory.GetFiles(Path.Combine(serverpath, art_foldername)).Count() > 0)
        //                                {
        //                                    string[] artFilesT = System.IO.Directory.GetFiles(Path.Combine(serverpath, art_foldername, artpdf_foldername), "*.*", SearchOption.AllDirectories).ToArray();

        //                                    foreach (string s in artFilesT)
        //                                    {
        //                                        if (!Directory.Exists(Path.Combine(filePath, "Temp", artpdf_foldername)))
        //                                        {
        //                                            Directory.CreateDirectory(Path.Combine(filePath, "Temp", artpdf_foldername));
        //                                        }

        //                                        System.IO.File.Copy(s, Path.Combine(filePath, "Temp", artpdf_foldername, Path.GetFileName(s)), true);
        //                                    }
        //                                }

        //                                string ce_files = Path.Combine(filePath, "Temp");

        //                                if (System.IO.File.Exists(Path.Combine(filePath, lottitle_zipfilename)))
        //                                {
        //                                    System.IO.File.Delete(Path.Combine(filePath, lottitle_zipfilename));
        //                                }

        //                                using (ZipFile outputZip = new ZipFile(Path.Combine(filePath, lottitle_zipfilename)))
        //                                {
        //                                    outputZip.AddDirectory(ce_files);
        //                                    outputZip.Save();
        //                                }

        //                                foreach (string s in Directory.GetFiles(ce_files, "*.*", SearchOption.AllDirectories))
        //                                {
        //                                    System.IO.File.Delete(s);
        //                                }
        //                                foreach (string d in Directory.GetDirectories(ce_files, "*", SearchOption.AllDirectories))
        //                                {
        //                                    Directory.Delete(d);
        //                                }
        //                                Directory.Delete(ce_files);

        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                Console.WriteLine(ex.Message.ToString());
        //                                return BadRequest(new { message = "Link is not valid" });
        //                            }
        //                        }
        //                        else
        //                        {
        //                            string[] filesT = System.IO.Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
        //                            string[] dirsT = System.IO.Directory.GetDirectories(serverpath, "*.*", SearchOption.AllDirectories);
        //                            if (filesT.Count() > 0 || dirsT.Count() > 0)
        //                            {
        //                                CreateZip(serverpath, Path.Combine(filePath, lottitle_zipfilename));

        //                            }
        //                        }

        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        Console.WriteLine(ex.Message.ToString());
        //                        return BadRequest(new { message = "Link is not valid" });
        //                    }
        //                }
        //                try
        //                {
        //                    /* string qry = "Select pd.serverroot from lot_transaction lt left outer join lot_master lm on lt.lotid=lm.lotid left outer join job_master jm on jm.jobid=lm.jobid left outer join project_definition pd on pd.projectdefinitionid=jm.projectdefinitionid where transactionid=" + dt.Rows[0]["transactionid"].ToString();
        //                     BLDatamanipulation dbSer = new BLDatamanipulation();
        //                     DataTable dtSer = dbSer.GetDataTable(db, qry, null);*/

        //                    //string serverpathdownload = Startup.Configuration.GetValue<string>("AppSettings:serverroot") + @"/" + Startup.Configuration.GetValue<string>("AppSettings:downloadspath") + @"/"
        //                    //                                + fileData.L.ToString().ToString().Trim() + @"/" + lottitle_zipfilename;
        //                    // string serverpathdownload = Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") + @"\" + fileData.L.ToString().ToString().Trim() + @"\" + lottitle_zipfilename;
        //                    string serverpathdownload = localpath + @"\" + fileData.L.ToString().ToString().Trim() + @"\" + lottitle_zipfilename;
        //                    if (serverpathdownload != "" || serverpathdownload.Length > 0)
        //                    {
        //                        byte[] file = System.IO.File.ReadAllBytes(serverpathdownload);
        //                        return Ok(new { File = file });
        //                    }
        //                    /* Response.Redirect(serverpathdownload, true);
        //                     Response.End();*/
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine(ex.Message.ToString());
        //                    return BadRequest(new { message = "Link is not valid" });
        //                }


        //            }
        //            else
        //            {
        //                return BadRequest(new { message = "Link is not valid" });
        //            }

        //        }
        //        else if (fileData.F != "")
        //        {
        //            var Book = fileData.B;
        //            var Query = fileData.Q;
        //            var Proof = fileData.P;
        //            var trankey = "";
        //            if (Query != null)
        //            {
        //                //trankey = Query;
        //                //using (DBContext _dbContext = new DBContext())
        //                //{
        //                //    BLDatamanipulation db = new BLDatamanipulation();
        //                //    Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@bookauthorkey", trankey.ToString()) };
        //                //    var dt1 = db.GetDataTable(_dbContext, "select transactionkey from query_author_details where bookauthorkey = @bookauthorkey and active = 1", sParams1);
        //                //    if (dt1.Rows.Count >= 0)
        //                //    {
        //                //        Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@bookauthorkey", trankey.ToString()) };
        //                //        var dt = db.GetDataTable(_dbContext, "select lotstatus,lotid,pickedby,transactionid from lot_transaction where transactionkey in (select transactionkey from query_author_details where bookauthorkey = @bookauthorkey and active = 1) and lotstatus != 'C'", sParams);
        //                //        if (dt.Rows.Count >= 0)
        //                //        {
        //                //            for (int i = 0; i <= dt.Rows.Count - 1; i++)
        //                //            {
        //                //                var pickedby = dt.Rows[i]["pickedby"].ToString();
        //                //                //if (pickedby == "0" || pickedby == "")
        //                //                //{
        //                //                var emaildetails = _dbContext.Database.SqlQuery<jsonvalue>("select * from  usr_email_info_job_query(@p_tranid,@p_wfdid, @p_option) as json",
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[i]["lotid"].ToString() },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_wfdid", Value = dt.Rows[i]["lotid"].ToString() },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "2" }).ToList();
        //                //                emaildata obj = JsonConvert.DeserializeObject<emaildata>(emaildetails[0].json);
        //                //                pickedby = obj.userid.ToString();

        //                //                var usr_lot_tran_update1 = _dbContext.Database.SqlQuery<jsonvalue>("select * from usr_lot_tran_update(@p_userid, @p_tranid,@p_holdreason,@p_option) as json",
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = pickedby },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[i]["transactionid"].ToString() },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_holdreason", Value = "" },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "checkin" }).ToList();
        //                //                // }
        //                //            }
        //                //        }
        //                //        else
        //                //        {
        //                //            ViewBag.msg = " Job is already completed";
        //                //            return View();
        //                //        }
        //                //    }
        //                //    else
        //                //    {
        //                //        ViewBag.msg = "Link is not valid";
        //                //        return View();
        //                //    }
        //                // }
        //            }
        //            else if (Book != null)
        //            {
        //                trankey = Book;
        //                //using (DBContext _dbContext = new DBContext())
        //                //{
        //                //    BLDatamanipulation db = new BLDatamanipulation();
        //                //    Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@bookauthorkey", trankey.ToString()) };
        //                //    var dt1 = db.GetDataTable(_dbContext, "select transactionkey from book_author_details where bookauthorkey = @bookauthorkey and active = 1", sParams1);
        //                //    if (dt1.Rows.Count >= 0)
        //                //    {
        //                //        Npgsql.NpgsqlParameter[] sParams = { new Npgsql.NpgsqlParameter("@bookauthorkey", trankey.ToString()) };
        //                //        var dt = db.GetDataTable(_dbContext, "select lotstatus,lotid,batchid,pickedby,transactionid,jobworkflowid from lot_transaction where transactionkey in (select transactionkey from book_author_details where bookauthorkey = @bookauthorkey and active = 1) and lotstatus != 'C'", sParams);

        //                //        if (dt.Rows.Count >= 0)
        //                //        {
        //                //            for (int i = 0; i <= dt.Rows.Count - 1; i++)
        //                //            {
        //                //                var pickedby = dt.Rows[i]["pickedby"].ToString();
        //                //                var stType = "LOT"; var ltid = dt.Rows[i]["lotid"].ToString();
        //                //                if (dt.Rows[i]["batchid"].ToString() != "")
        //                //                {
        //                //                    stType = "BATCH";
        //                //                    ltid = dt.Rows[i]["batchid"].ToString();
        //                //                }


        //                //                var emaildetails = _dbContext.Database.SqlQuery<jsonvalue>("select * from  usr_email_info_JOB(@p_tranid,@p_wfdid, @p_option) as json",
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = ltid },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_wfdid", Value = dt.Rows[i]["jobworkflowid"].ToString() },
        //                //                new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "1" }).ToList();
        //                //                if (emaildetails.Count > 0)
        //                //                {
        //                //                    emaildata obj = JsonConvert.DeserializeObject<emaildata>(emaildetails[0].json);
        //                //                    pickedby = obj.userid.ToString();

        //                //                    var usr_lot_tran_update1 = _dbContext.Database.SqlQuery<jsonvalue>("select * from usr_lot_tran_update(@p_userid, @p_tranid,@p_holdreason,@p_option) as json",
        //                //                    new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = pickedby },
        //                //                    new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = dt.Rows[i]["transactionid"].ToString() },
        //                //                    new Npgsql.NpgsqlParameter { ParameterName = "@p_holdreason", Value = "" },
        //                //                    new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "checkin" }).ToList();
        //                //                    // }
        //                //                }
        //                //            }
        //                //        }
        //                //        else
        //                //        {
        //                //            ViewBag.msg = " Job is already completed";
        //                //            return View();
        //                //        }
        //                //    }
        //                //    else
        //                //    {
        //                //        ViewBag.msg = "Link is not valid";
        //                //        return View();
        //                //    }
        //                //}
        //            }
        //            else if (Proof != null)
        //            {
        //                //trankey = Proof;
        //                //var userid = Request.QueryString["U"];
        //                //using (DBContext _dbContext = new DBContext())
        //                //{
        //                //    BLDatamanipulation db = new BLDatamanipulation();
        //                //    Npgsql.NpgsqlParameter[] sParams1 = { new Npgsql.NpgsqlParameter("@bookauthorkey", trankey.ToString()), new Npgsql.NpgsqlParameter("@userid", userid.ToString()) };
        //                //    var dt1 = db.GetDataTable(_dbContext, "select count(*) as stotal from book_proof_details a where  a.bookproofkey = @bookauthorkey and userid = @userid and active = 1 and status in ('R','P')", sParams1);
        //                //    if (dt1.Rows.Count >= 0)
        //                //    {
        //                //        if (dt1.Rows[0][0].ToString() == "0")
        //                //        {
        //                //            ViewBag.msg = " Job is already completed";
        //                //            return View();
        //                //        }

        //                //        var emaildetails = _dbContext.Database.SqlQuery<jsonvalue>("select * from  set_book_proof_details_update_status(@p_tranid, @p_status,@p_userid) as json",
        //                //    new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trankey.ToString() },
        //                //    new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = "P" },
        //                //    new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = userid }).ToList();

        //                //    }
        //                //    else
        //                //    {
        //                //        ViewBag.msg = "Link is not valid";
        //                //        return View();
        //                //    }
        //                // }
        //            }
        //            else
        //            {
        //                // july02 for download file with keyinjection start
        //                trankey = fileData.L.ToString().Trim();
        //                var dt = oUploaderService.getlotstatusbytrankey(trankey);
        //                if (dt == null)
        //                {
        //                    return BadRequest(new { message = "Link is not valid" });
        //                }
        //                var i1_dt = JsonConvert.DeserializeObject<object>(dt.ToString());
        //                JArray a1_dt = JArray.Parse(i1_dt.ToString());
        //                JObject obj1_dt = JObject.Parse(a1_dt[0].ToString());
        //                if (obj1_dt["lotstatus"].ToString() == "C")
        //                {
        //                    return BadRequest(new { message = "Job is already completed" });
        //                }
        //                int _transactionid = Convert.ToInt32(fileData.T.ToString());
        //                string filePath_tmp = oCommonRepository.getfilesavelocation(_transactionid);
        //                filePath_tmp = oCommonRepository.FormatPath(filePath_tmp);
        //                string filePath_server = oCommonRepository.GetServerPath(_transactionid.ToString(), "serverinfo", false);
        //                filePath_server = filePath_server.Replace("/", "\\");
        //                var filePath_IN = Path.Combine(filePath_server, "IN");
        //                var serverPath_tmp = string.Empty;
        //                if (filePath_tmp != string.Empty)
        //                {
        //                    serverPath_tmp = Path.Combine(filePath_tmp, "UploadFiles", _transactionid.ToString(), fileData.L.ToString().ToString().Trim());
        //                    if (!Directory.Exists(serverPath_tmp))
        //                        Directory.CreateDirectory(serverPath_tmp);
        //                }

        //                var pickedby = obj1_dt["pickedby"].ToString();

        //                if (pickedby == "0" || pickedby == "")
        //                {
        //                    var emaildetails = oUploaderService.usremailinfojob(Convert.ToInt32(obj1_dt["lotid"].ToString()), Convert.ToInt32(obj1_dt["jobworkflowid"].ToString()));

        //                    if (emaildetails != null)
        //                    {
        //                        var i1_emaildetails = JsonConvert.DeserializeObject<object>(emaildetails.ToString());
        //                        JArray a1_emaildetails = JArray.Parse(i1_emaildetails.ToString());
        //                        JObject obj1_emaildetails = JObject.Parse(a1_emaildetails[0].ToString());

        //                        pickedby = fileData.U.ToString();//obj1_emaildetails["pickedby"].ToString();
        //                        //string tranid, string userid, string status, string option, string jobworkflowid, string comments
        //                        var usr_lot_tran_update1 = oWorkAreaService.getCheckout(obj1_dt["transactionid"].ToString(), pickedby, "P", "checkin", "0", "");

        //                    }
        //                }
        //                string zipfile = Path.Combine(serverPath_tmp, fileData.F.ToString());
        //                if (System.IO.File.Exists(zipfile))
        //                    System.IO.File.Delete(zipfile);
        //                string[] filesT = System.IO.Directory.GetFiles(filePath_IN, "*.*", SearchOption.AllDirectories);
        //                string[] dirsT = System.IO.Directory.GetDirectories(filePath_IN, "*.*", SearchOption.AllDirectories);
        //                if (filesT.Count() > 0 || dirsT.Count() > 0)
        //                {
        //                    var getdoc = System.IO.Directory.GetFiles(filePath_IN, "*.*", SearchOption.AllDirectories).Where(x => Path.GetExtension(x.ToString()).ToLower().Contains(".docx"));
        //                    if (getdoc.Count() == 1) // inject unique key in docx file only if IN path has only one document file.
        //                    {
        //                        try
        //                        {
        //                            var backupDir = oCommonRepository.GetBackupfolder(System.IO.Path.Combine(filePath_server, "V001"));
        //                            oCommonRepository.CopyDirectory(filePath_server.ToString(), backupDir.ToString());
        //                            string ExeName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Startup.Configuration.GetValue<string>("AppSettings:KEYCHANGER").ToString());
        //                            runexe(ExeName, "\"" + getdoc.FirstOrDefault() + "\"" + " \"" + trankey + "\"");
        //                        }
        //                        catch (Exception ex)
        //                        {
        //                            Console.WriteLine(ex.Message.ToString());
        //                            return BadRequest(new { message = "Link is not valid" });
        //                        }
        //                    }  
        //                    CreateZip(filePath_IN, Path.Combine(serverPath_tmp, fileData.F.ToString()));
        //                    if (serverPath_tmp != "" || serverPath_tmp.Length > 0)
        //                    {
        //                        byte[] file = System.IO.File.ReadAllBytes(Path.Combine(serverPath_tmp, fileData.F.ToString()));
        //                        return Ok(new { File = file });
        //                    }
        //                }
        //                // july02 for download file with keyinjection End
        //            }

        //            //  string serverpathdownload = Startup.Configuration.GetValue<string>("AppSettings:serverroot") + @"/" + Startup.Configuration.GetValue<string>("AppSettings:downloadspath") + @"/" +  trankey + @"/" + fileData.F.ToString().ToString().Trim();

        //            // string serverpathdownload = Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") +   fileData.L.ToString().ToString().Trim() + @"\" + fileData.F.ToString().ToString().Trim();


        //        }

        //        return Ok();
        //    }

        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.Message.ToString());
        //        return BadRequest(new { message = "Link is not valid" });
        //    }
        //}
        [AllowAnonymous]
        [HttpPost("Downloader")]
        public IActionResult Downloader(dynamic fileData)
        {
            try
            {
                string fileDataJson = System.Text.Json.JsonSerializer.Serialize(fileData);
                using (JsonDocument doc = JsonDocument.Parse(fileDataJson))
                {
                    JsonElement fileDataparse = doc.RootElement;
                    string filename = string.Empty;
                    string base64String = string.Empty;
                    string F = fileDataparse.GetProperty("F").GetString(); //filename
                    int U = fileDataparse.GetProperty("U").GetInt32(); //userid
                    string L = fileDataparse.GetProperty("L").GetString(); //trankey
                    int T = fileDataparse.GetProperty("T").GetInt32(); //tranid
                    string K = fileDataparse.GetProperty("K").GetString(); //filename
                    byte[] file = null;
                    string lotid = string.Empty;
                    //if (F.EndsWith(".pdf"))
                    //{
                    //    filename = F.Substring(0, F.Length - 4);
                    //}
                    filename = $"{K}-{U}";
                    string zipfileName = filename + ".zip";
                    if (!string.IsNullOrEmpty(K))
                    {
                      
                        var data1 = new { vendorkey = K, p_option = "getlotstatusbyvendorkey" };
                        var jsonstr1 = JsonConvert.SerializeObject(data1);
                        var next_ordernores1 = oCommonRepository.ExecuteSP_ReturnList1("sppostupdatelottransaction", jsonstr1);
                        var next_ordernodata1 = JsonConvert.DeserializeObject<object>(next_ordernores1.ToString());
                        JArray LotDetails = JArray.Parse(next_ordernodata1.ToString());

                        string zipFilePath = string.Empty;
                        string Zip_filePath_server = string.Empty;
                        if (LotDetails.Count > 0)
                        {
                            JObject firstElement = (JObject)LotDetails[0];
                             lotid = firstElement["lotid"].ToString();
                            string jobid = firstElement["jobid"].ToString();
                            string lotstatus = firstElement["lotstatus"].ToString();
                            if (lotstatus == "C")
                            {
                                return BadRequest(new { message = "Job is already completed" });
                            }
                            
                            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", lotid))
                            {
                                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                                {
                                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                                    Zip_filePath_server = oCommonRepository.GetServerPath(jobid, "serverinfo_job", false);
                                    Zip_filePath_server = Path.Combine(Zip_filePath_server, "VendorAllocation","download",U.ToString(),K);
                                    if (!Directory.Exists(Zip_filePath_server)) Directory.CreateDirectory(Zip_filePath_server);
                                     zipFilePath = Path.Combine(Zip_filePath_server, zipfileName);
                                    // Create or open the zip file
                                  //  while (IsFileLocked(zipFilePath))
                                   // {
                                        using (var zipToOpen = new FileStream(zipFilePath, FileMode.Create))
                                        {
                                          //  while (IsFileLocked(zipFilePath))
                                          //  {
                                                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                                                {
                                                    for (var item = 0; item < LotDetails.Count; item++)
                                                    {
                                                        lotid = LotDetails[item]["lotid"].ToString();
                                                        int _transactionid = Convert.ToInt32(LotDetails[item]["transactionid"]);
                                                        string filePath_server = oCommonRepository.GetServerPath(_transactionid.ToString(), "serverinfo", false);
                                                        filePath_server = filePath_server.Replace("/", "\\");
                                                        var filePath_IN = Path.Combine(filePath_server, "IN");
                                                        var files = Directory.EnumerateFiles(filePath_IN, "*.*", SearchOption.TopDirectoryOnly)
                       .Where(file => file.EndsWith(".doc", StringComparison.OrdinalIgnoreCase) ||
                       file.EndsWith(".docx", StringComparison.OrdinalIgnoreCase) ||
                        file.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase));

                                                        foreach (string file in files)
                                                        {
                                                            if (System.IO.File.Exists(file))
                                                            {
                                                                AddFileToArchive(archive, file);
                                                            }
                                                        }
                                                    }//end loop
                                                }
                                           // }
                                        }
                                    //}
                                    if (System.IO.File.Exists(zipFilePath))
                                    {
                                        //while (IsFileLocked(zipFilePath))
                                       // {
                                            file = System.IO.File.ReadAllBytes(zipFilePath);
                                            base64String = Convert.ToBase64String(file);
                                            // Wait before retrying
                                          //  System.Threading.Thread.Sleep(500);
                                       // }
                                      
                                    }
                                });
                                }
                        }
                        else
                        {
                            return BadRequest(new { message = "Link is not valid" });
                        }
                    }
                    else
                    {
                    if (!string.IsNullOrEmpty(F))
                    {
                            var dt = oUploaderService.getlotstatusbytrankey(L.ToString().Trim());
                            if (dt == null)
                            {
                                return BadRequest(new { message = "Link is not valid" });
                            }
                            var i1_dt = JsonConvert.DeserializeObject<object>(dt.ToString());
                            JArray a1_dt = JArray.Parse(i1_dt.ToString());
                            JObject obj1_dt = JObject.Parse(a1_dt[0].ToString());
                            if (obj1_dt["lotstatus"].ToString() == "C")
                            {
                                return BadRequest(new { message = "Job is already completed" });
                            }
                        lotid = obj1_dt["lotid"].ToString();
                            int _transactionid = Convert.ToInt32(T.ToString());
                            string filePath_tmp = oCommonRepository.getfilesavelocation(_transactionid);
                            filePath_tmp = oCommonRepository.FormatPath(filePath_tmp);
                            string filePath_server = oCommonRepository.GetServerPath(_transactionid.ToString(), "serverinfo", false);
                            filePath_server = filePath_server.Replace("/", "\\");
                            var filePath_IN = Path.Combine(filePath_server, "IN");
                            var serverPath_tmp = string.Empty;

                            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("","", obj1_dt["lotid"].ToString()))
                            {
                                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                                {
                                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                                    System.Console.WriteLine(useri.Name);
                                    
                                    string zipFilePath = Path.Combine(filePath_IN, zipfileName);
                                    // Create or open the zip file
                                    using (var zipToOpen = new FileStream(zipFilePath, FileMode.Create))
                                    {
                                        using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                                        {
                                            // Add all folders and their contents to the zip file
                                            //foreach (string folder in Directory.EnumerateDirectories(directoryPath, "*", SearchOption.TopDirectoryOnly))
                                            //{
                                            //    AddFolderToArchive(archive, folder, Path.GetFileName(folder));
                                            //}

                                            // Add all Word documents to the zip file
                                            var files = Directory.EnumerateFiles(filePath_IN, "*.*", SearchOption.TopDirectoryOnly)
                     .Where(file => file.EndsWith(".doc", StringComparison.OrdinalIgnoreCase) ||
                     file.EndsWith(".docx", StringComparison.OrdinalIgnoreCase) ||
                      file.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase));

                                            foreach (string file in files)
                                            {
                                                if (System.IO.File.Exists(file))
                                                {
                                                    AddFileToArchive(archive, file);
                                                }
                                            }
                                        }
                                    }
                                    string downloadzipFilePath = Path.Combine(filePath_IN, zipfileName);
                                    
                                    if (System.IO.File.Exists(downloadzipFilePath))
                                            {
                                                file = System.IO.File.ReadAllBytes(downloadzipFilePath);

                                                Console.WriteLine("ZIP file read successfully.");
                                        //return File(file, "application/zip", zipfileName);
                                         base64String = Convert.ToBase64String(file);
                                    
                                    } 
                                });
                        }
                    }
                    }
                    // return Ok(new { File = file });
                    return Ok(new { File = base64String, FileName = zipfileName, lotid= lotid });
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return BadRequest(new { message = "Link is not valid" });
            }
        }
        public bool IsFileLocked(string filePath)
        {
            try
            {
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    stream.Close();
                }
            }
            catch (IOException)
            {
                // File is being used by another process
                return true;
            }
            catch (Exception ex)
            {
                // Handle unexpected exceptions, if necessary
                throw new Exception("An error occurred while checking the file.", ex);
            }

            // No exception means the file is not locked
            return false;
        }
        static void AddFileToArchive(ZipArchive archive, string filePath)
        {
            try
            {
                string entryName = Path.GetFileName(filePath);
                ZipArchiveEntry zipEntry = archive.CreateEntry(entryName);

                using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                using (var entryStream = zipEntry.Open())
                {
                    fileStream.CopyTo(entryStream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to add file {filePath}: {ex.Message}");
            }
        }
        [AllowAnonymous]
        [HttpPost("UploadFile")]
        public IActionResult UploadFile()
        {
            string msg = "";
            try
            {
                foreach (var file in HttpContext.Request.Form.Files)
                {

                    var FileDataContent = file;//HttpContext.Request.Form.Files[file.ToString()];
                    if (FileDataContent != null && FileDataContent.Length > 0)
                    {
                        var stream = FileDataContent;
                        var fileName = Path.GetFileName(FileDataContent.FileName).Split('~')[0];
                        var trankey = Path.GetFileName(FileDataContent.FileName).Split('~')[1];
                        var tranid = Path.GetFileName(FileDataContent.FileName).Split('~')[2];
                        var userid = Path.GetFileName(FileDataContent.FileName).Split('~')[3];
                        string key = Path.GetFileName(FileDataContent.FileName).Split('~')[4];
                        string localpath = ""; 
                        int _transactionid = Convert.ToInt32(tranid.ToString());
                        string filePath_tmp = oCommonRepository.getfilesavelocation(_transactionid);
                        filePath_tmp = filePath_tmp.Replace("/", "\\");
                        filePath_tmp = @"\\" + filePath_tmp;
                        using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid))
                        {
                            WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                            WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                            {
                                WindowsIdentity useri = WindowsIdentity.GetCurrent();
                                System.Console.WriteLine(useri.Name);
                                if (filePath_tmp != string.Empty)
                                {
                                    var serverPath_tmp = Path.Combine(filePath_tmp, "UploadFiles");
                                    if (!Directory.Exists(serverPath_tmp))
                                        Directory.CreateDirectory(serverPath_tmp);
                                    var serverPath_tranid = Path.Combine(serverPath_tmp, _transactionid.ToString());
                                    if (!Directory.Exists(serverPath_tranid))
                                        Directory.CreateDirectory(serverPath_tranid);
                                    localpath = serverPath_tranid;
                                }
                                string UploadPath = localpath + @"\From";
                                string UploadPath_ = localpath + @"\From";

                                if (!Directory.Exists(UploadPath))
                                    Directory.CreateDirectory(UploadPath);

                                string path = Path.Combine(UploadPath, fileName);

                                if (System.IO.File.Exists(path))
                                    System.IO.File.Delete(path);
                                using (var fileStream = System.IO.File.Create(path))
                                {
                                    stream.CopyTo(fileStream);
                                }
                                MergedFile_Service UT = new MergedFile_Service();
                                if (UT.MergeFile(path, userid, UploadPath_, trankey, "", tranid, key))
                                {
                                    //Job_Header_Id = UT.Job_Header_Id;
                                }
                                msg = UT.ReturnMsg;
                            });
                        }
                    }
                }
                return Ok(msg);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return BadRequest(new { message = "Link is not valid" });
            }
            //return msg;
        }
        //[AllowAnonymous]
        //[HttpPost("UploadFile")]

        //public IActionResult UploadFile()
        //{
        //    string msg = "";
        //    // var httpRequest = HttpContext.Request.Form;
        //    try
        //    {
        //        foreach (var file in HttpContext.Request.Form.Files)
        //        {
        //            var FileDataContent = file;//HttpContext.Request.Form.Files[file.ToString()];
        //            if (FileDataContent != null && FileDataContent.Length > 0)
        //            {
        //                var stream = FileDataContent;
        //                var fileName = Path.GetFileName(FileDataContent.FileName).Split('~')[0];
        //                var trankey = Path.GetFileName(FileDataContent.FileName).Split('~')[1];
        //                var tranid = Path.GetFileName(FileDataContent.FileName).Split('~')[2];
        //                var userid = Path.GetFileName(FileDataContent.FileName).Split('~')[3];
        //                var key = Path.GetFileName(FileDataContent.FileName).Split('~')[4];
        //                string localpath = ""; //Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") + @"/" + fileData.L.ToString().ToString().Trim() + @"/" + lottitle_zipfilename;
        //                int _transactionid = Convert.ToInt32(tranid.ToString());
        //                string filePath_tmp = oCommonRepository.getfilesavelocation(_transactionid);
        //                filePath_tmp = filePath_tmp.Replace("/", "\\");
        //                filePath_tmp = @"\\" + filePath_tmp;
        //                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid))
        //                {
        //                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

        //                    WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
        //                    {
        //                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
        //                        System.Console.WriteLine(useri.Name);
        //                        if (filePath_tmp != string.Empty)
        //                        {
        //                            var serverPath_tmp = Path.Combine(filePath_tmp, "UploadFiles");
        //                            if (!Directory.Exists(serverPath_tmp))
        //                                Directory.CreateDirectory(serverPath_tmp);
        //                            var serverPath_tranid = Path.Combine(serverPath_tmp, _transactionid.ToString());
        //                            if (!Directory.Exists(serverPath_tranid))
        //                                Directory.CreateDirectory(serverPath_tranid);
        //                            localpath = serverPath_tranid;
        //                        }
        //                        //string UploadPath = Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") + @"\From";
        //                        //string UploadPath_ = Startup.Configuration.GetValue<string>("AppSettings:serverfilepath") + @"\From";
        //                        string UploadPath = localpath + @"\From";
        //                        string UploadPath_ = localpath + @"\From";

        //                        if (!Directory.Exists(UploadPath))
        //                            Directory.CreateDirectory(UploadPath);
        //                        Directory.CreateDirectory(UploadPath); Directory.CreateDirectory(UploadPath_);
        //                        string path = Path.Combine(UploadPath, fileName);

        //                        if (System.IO.File.Exists(path))
        //                            System.IO.File.Delete(path);
        //                        using (var fileStream = System.IO.File.Create(path))
        //                        {
        //                            stream.CopyTo(fileStream);
        //                        }
        //                        MergedFile_Service UT = new MergedFile_Service();
        //                        if (UT.MergeFile(path, userid, UploadPath_, trankey, "", tranid))
        //                        {
        //                            //Job_Header_Id = UT.Job_Header_Id;
        //                        }
        //                        msg = UT.ReturnMsg;
        //                    });
        //                }
        //            }

        //        }
        //        return Ok(msg);
        //    }
        //    catch (IOException ex)
        //    {
        //        Console.WriteLine(ex.Message.ToString());
        //        return BadRequest(new { message = "Link is not valid" });
        //    }
        //    //return msg;
        //}

        [AllowAnonymous]
        [HttpPost("ValidateJob/{trankey}")]
        public IActionResult ValidateJob(string trankey)
        {
            try
            {
                var lotstatus = oUploaderService.getlotstatusbytrankey(trankey);
                return Ok(lotstatus);

                //if (lotstatus != null)
                //{
                //    var i1_lotstatus = JsonConvert.DeserializeObject<object>(lotstatus.ToString());
                //    JArray a1_lotstatus = JArray.Parse(i1_lotstatus.ToString());
                //    JObject obj1_lotstatus = JObject.Parse(a1_lotstatus[0].ToString());
                //    return Ok(obj1_lotstatus["lotstatus"].ToString());

                //}
                //else
                //{
                //    return  Ok("Job not Avaliable");
                //}                     

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [AllowAnonymous]
        [HttpPost("getJobDetails/{trankey}")]
        public IActionResult getJobDetails(string trankey)
        {
            try
            {
                var list = oUploaderService.getJobDetails(trankey);
                return Ok(list);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //private void CreateZip(string directoryPathToZip, string outputZipFileName)
        //{
        //    try
        //    {
        //        if (System.IO.File.Exists(outputZipFileName))
        //        {
        //            System.IO.File.Delete(outputZipFileName);
        //        }
        //        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        //        using (ZipFile outputZip = new ZipFile(outputZipFileName))
        //        {
        //            outputZip.AddDirectory(directoryPathToZip);
        //            outputZip.Save();
        //        }
        //    }
        //    catch (Exception ex)
        //    { Console.WriteLine(ex.Message.ToString()); }

        //}
        public static string ErrorMsg = "";
        public static string runexe(string ExeName, string Params)
        {
            Process compare = new Process();
            try
            {
                //ExeName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tools\\KEYCHANGER\\LAPS_PWD_Injector.exe");
                //Params = @"E:\KLI_Laps2\27Jun2020\STWORKFLOW\WK_KLI_LAPS_Service\WK_KLI_LAPS_Service\Uploadfiles\2056\K35650_C000.docx""10f69c43-9ffe-fb88-3678-c46015faca84""";
                compare.StartInfo.FileName = ExeName;
                compare.StartInfo.Arguments = Params;
                compare.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                compare.StartInfo.WorkingDirectory = Path.GetDirectoryName(ExeName);
                compare.Start();
                compare.WaitForExit();
                if (ErrorMsg != "") return ErrorMsg;
            }
            catch (Exception exp) { ErrorMsg = "Error while conversion, exception is: " + exp.Message + "::" + exp.StackTrace; }
            finally { if (compare != null) compare.Close(); }
            return ErrorMsg;
        }
    }
}
