using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;										

namespace WK_KLI_LAPS_Service.Controllers.Master.Lot
{
    [Route("api/[controller]")]
    [ApiController]
    public class LotApiController : ControllerBase
    {
        CommonRepository oCommonRepository = new CommonRepository();
        MasterRepository oMasterRepository = new MasterRepository();
        private ILotService _LotService;
        public LotApiController(ILotService LotService)
        {
            _LotService = LotService;

        }

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

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


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

        }


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


        [Authorize]
        [HttpPost("GetByJobId")]
        public IActionResult GetByJobId([FromBody] lotmasterModel data)
        {
            try
            {
                var list = _LotService.GetByJobId(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        [Authorize]
        [HttpPost("GetBylotProjectId")]
        public IActionResult GetBylotProjectId([FromBody] lotmasterModel data)
        {
            try
            {
                var list = _LotService.GetBylotProjectId(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("GetBylotId")]
        public IActionResult GetBylotId([FromBody] lotmasterModel data)
        {
            try
            {
                var list = _LotService.GetBylotId(data);
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("UploadLotFile")]
        public IActionResult UploadLotFile([FromForm] lotmasterModel ouserModel)
        {
            try
            {
                string fileName = string.Empty;
                string lotid = string.Empty;
                string jobid = string.Empty;
                string instruction = string.Empty;
                int chaptype = 0;
                bool isgraphic = false;

                string serverpath = string.Empty;
                string sParentPath = string.Empty;
                string serverpath1 = string.Empty;
                string previousid = string.Empty;
                string artinfo = string.Empty;
                string sFilePath = string.Empty;

                var httpRequest = HttpContext.Request.Form;
                for (int file = 0; file < HttpContext.Request.Form.Files.Count; file++)
                {
                    var FileDataContent = HttpContext.Request.Form.Files[file];
                    if (FileDataContent != null && FileDataContent.Length > 0)
                    {
                        // take the input stream, and save it to a temp folder using the original file.part name posted
                        var stream = FileDataContent;
                        string[] col = Path.GetFileName(FileDataContent.FileName).Split('~');
                        fileName = col[0];
                        lotid = col[1];
                        jobid = col[2];
                        instruction = col[3];
                        chaptype = 0;
                        isgraphic = false;

                        if (col.Length > 4)
                        { chaptype = Convert.ToInt32(col[4]); isgraphic = Convert.ToBoolean(col[5]); }

                        // string serverpath = GetServerPath(jobid.ToString(), true, "serverinfo_job");
                        // string sFilePath = Path.Combine(serverpath, fileName.ToString());
                        var data = new
                        {
                            errormessage = lotid.ToString(),
                            createdby = 0,
                            controller = "LotApi:UploadLotFile - lotid"
                        };
                        int retval = oMasterRepository.addlog(data, "errorlog");

                        serverpath = GetServerPath(lotid.ToString(), true, "serverinfo_lot");
                        var data1 = new
                        {
                            errormessage = (serverpath + " ").ToString(),
                            createdby = 0,
                            controller = "LotApi: UploadLotFile-serverpath"
                        };
                        retval = oCommonRepository.addlog(data1, "errorlog");
                        sParentPath = Path.Combine(Path.GetDirectoryName(serverpath), "Parent");
                        data1 = new
                        {
                            errormessage = (sParentPath + " ").ToString(),
                            createdby = 0,
                            controller = "LotApi: UploadLotFile-sParentPath2"
                        };
                        if (!Directory.Exists(sParentPath))
                            Directory.CreateDirectory(sParentPath);
                        serverpath1 = Path.Combine(serverpath, "IN");

                        data1 = new
                        {
                            errormessage = ("File created" + " ").ToString(),
                            createdby = 0,
                            controller = "LotApi: File created"
                        };
                        retval = oCommonRepository.addlog(data1, "errorlog");

                        if (isgraphic)
                        {
                            if (!Directory.Exists(Path.Combine(serverpath1, "Graphics")))
                                Directory.CreateDirectory(Path.Combine(serverpath1, "Graphics"));
                            if (!Directory.Exists(Path.Combine(sParentPath, "Graphics")))
                                Directory.CreateDirectory(Path.Combine(sParentPath, "Graphics"));

                        }
                        sFilePath = Path.Combine(serverpath1, (isgraphic ? "Graphics" : ""), fileName.ToString());

                        if (System.IO.File.Exists(sFilePath))
                        {
                            System.IO.File.Delete(sFilePath);
                        }
                        try
                        {
                            using (var fileStream = System.IO.File.Create(sFilePath))
                            {
                                stream.CopyTo(fileStream);
                            }
                        }

                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message.ToString());
                            throw;
                        }
                    }
                }
                return Ok();
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                var data1 = new
                {
                    errormessage = (ex.Message + " ").ToString(),
                    createdby = 0,
                    controller = "LotApi: Upload file:Error"
                };
                oCommonRepository.addlog(data1, "errorlog");
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("UploadLotInfoExcelFile")]
        public IActionResult UploadLotInfoExcelFile([FromForm] jobModel ojobModel)
        {
            try
            {
                var retval = new List<object>();
                string sFilePath = string.Empty;
                string jtitle =Request.Form["title"].ToString();
                string jobid =Request.Form["jobid"].ToString();
                string projectdefinitionid = Request.Form["projectdefinitionid"].ToString();
                string userid = Request.Form["userid"].ToString();
                string stcode = Request.Form["statecode"].ToString();
                string ftype = Request.Form["frequencetype"].ToString();

                string serverpath = GetServerPath(projectdefinitionid, true, "serverinfo_projid");
                string[] jobdate = jtitle.Split("_");
                string foldername = string.Concat("LotInfoExcel_", jobdate[1]);
                string serverpath1 = Path.Combine(serverpath, foldername);
                if (Directory.Exists(serverpath1))
                {
                    if(Directory.GetFiles(serverpath1).Length>0)
                        sFilePath = Directory.GetFiles(serverpath1)[0];
                    else
                        return BadRequest(new { message = "File missting" });
                }
                else
                    return BadRequest(new { message = "File missting" });

                List<lotinfoexcellist> lotlist = new List<lotinfoexcellist>();
                using (ExcelPackage package = new ExcelPackage(new FileInfo(sFilePath)))
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    ExcelWorksheet worksheet = null;
                    worksheet = package.Workbook.Worksheets["sheet1"];
                    //for (int i = 0; i < package.Workbook.Worksheets.Count; i++)
                    //{
                    //    if (package.Workbook.Worksheets[i].Name == jtitle)
                    //    {
                    //        worksheet = package.Workbook.Worksheets[jtitle];
                    //    }
                    //    else
                    //    {
                    //        return BadRequest(new { message = "Invalid Excel File. Kindly upload valid excel." });
                    //    }
                    //}
                    int colCount = worksheet.Dimension.End.Column;  //get Column Count
                    int rowCount = worksheet.Dimension.End.Row;     //get row count
                    for (int row = 2; row <= rowCount; row++)
                    {
                        bool st = false;
                        bool ft = false;
                        if (worksheet.Cells[row, 5].Value?.ToString().Trim() == ftype)
                            ft = true;

                        if (worksheet.Cells[row, 7].Value?.ToString().Trim() == stcode)
                            st = true;

                        lotinfoexcellist lotitem = new lotinfoexcellist();
                        if (ft && st)
                        {
                            lotitem.CompanyName = worksheet.Cells[row, 2].Value?.ToString().Trim();
                            lotitem.Frequency = worksheet.Cells[row, 5].Value?.ToString().Trim();
                            lotitem.State = worksheet.Cells[row, 7].Value?.ToString().Trim();
                            lotitem.FollowUpDate = worksheet.Cells[row, 8].Value?.ToString().Trim();
                            lotitem.Status = worksheet.Cells[row, 9].Value?.ToString().Trim();
                            lotlist.Add(lotitem);
                        }
                    }

                }
                try
                {
                    lotmasterModel olotmaster = new lotmasterModel();
                    olotmaster.jobid = Convert.ToInt32(jobid);
                    olotmaster.createdby = Convert.ToInt32(userid);
                    olotmaster.option = "insertlot";
                    string inputstr = JsonConvert.SerializeObject(olotmaster);
                    for (int nwlot = 1; nwlot <= lotlist.Count; nwlot++)
                    {
                        var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                        retval.Add(retval1);
                    }
                }
                catch (Exception ex)
                {
                    oCommonRepository.ErrorLog(ex);
                    return BadRequest(new { message = ex.Message });
                }
                return Ok(retval);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string FormatPath(string inputpath)
        {
            try
            {
                inputpath = inputpath.Replace("/", "\\");
                inputpath = inputpath.Replace("\\\\", "");
                inputpath = System.Text.RegularExpressions.Regex.Replace(inputpath, @"\\\\", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return string.Concat("\\\\", inputpath);
        }



        public string GetServerPath(string transactionid, bool createdir = false, string serverinfo = "")
        {
            string serverpath = string.Empty;
            try
            {
                var data = new
                {
                    transactionid = transactionid,
                    lotid = 0,
                    option = serverinfo
                };

                string inputstr = JsonConvert.SerializeObject(data);
                var ds = _LotService.GetServerPath(inputstr);
                // DataSet ds = GetDataTable("usr_server_path_info", GetNpgsqlParameter(transactionid, 0, serverinfo));
                var data1 = new
                {
                    errormessage = ds.serverpath.ToString(),
                    createdby = 0,
                    controller = "LotApi:GetServerPath - ds.serverpath"
                };
                int retval = oMasterRepository.addlog(data1, "errorlog");
                if (createdir)
                {
                    //if (ds)
                    // {
                    string username = ds.username;
                    string password = ds.password;
                    string domain = ds.domain;
                    bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    if (isWindows)
                    {
                        serverpath = FormatPath(ds.serverpath);
                    }
                    else
                    {
                        serverpath = ds.serverpath;
                    }

                    var data2 = new
                    {
                        errormessage = serverpath.ToString(),
                        createdby = 0,
                        controller = "LotApi:GetServerPath - serverpath after format"
                    };
                    int retval1 = oMasterRepository.addlog(data2, "errorlog");

                    if (username != "" && password != "")
                    {
                        // Impartunate impart = new Impartunate(username, password, domain);
                        // if (impart.AllowAccesstoServer())
                        {
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        //impart.RemoveServerAccess();
                    }
                    else
                    {
                        Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                        Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        Directory.CreateDirectory(serverpath);
                    }
                    // }
                }
                else
                {
                    serverpath = FormatPath(ds.serverpath); // GetPath(query);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return serverpath;
            }
            return serverpath;
        }
        [AllowAnonymous]
        [HttpGet("connectlinux")]
        public IActionResult connectlinux()
        {
            try
            {
                var list = oCommonRepository.connectlinux();
                return Ok(list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }
        //ccwms
        [Authorize]
        [HttpPost("AddCCLotMaster")]
        public IActionResult AddCCLotMaster([FromBody] lotmasterModel olotmaster)
        {
            try
            {
                //string inputstr = JsonConvert.SerializeObject(olotmaster);
                if (olotmaster.jobid == 0)
                {
                    //var _list = _JobConfigurationservices.PostCCJobMaster(olotmaster.createdby, 349);
                    var _list= oMasterRepository.PostCCJobMaster("cc_sp_createjob",Convert.ToInt64(olotmaster.createdby), 349);
                    jobModel json = new jobModel();
                    json =JsonConvert.DeserializeObject<jobModel>(_list.ToString());
                    olotmaster.jobid =Convert.ToInt32(json.jobid);
                }
                var retval = _LotService.AddCCLotMaster(olotmaster, "cc_sp_createlot1");
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        } 
        [Authorize]
        [HttpPost("AddCCLotMasterandtrans")]
        public IActionResult AddCCLotMasterandtrans([FromBody] lotmasterModel olotmaster)
        {
            try
            {
                //string inputstr = JsonConvert.SerializeObject(olotmaster);
                if (olotmaster.jobid == 0)
                {
                    //var _list = _JobConfigurationservices.PostCCJobMaster(olotmaster.createdby, 349);
                    var _list= oMasterRepository.PostCCJobMaster("cc_sp_createjob",Convert.ToInt64(olotmaster.createdby), 349);
                    jobModel json = new jobModel();
                    json =JsonConvert.DeserializeObject<jobModel>(_list.ToString());
                    olotmaster.jobid =Convert.ToInt32(json.jobid);
                }
                string inputstr = JsonConvert.SerializeObject(olotmaster);
                var retval = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }
        }

        //[Authorize]
        //[HttpPost("Putlotmetafields")]
        //public IActionResult Putlotmetafields([FromBody] lotmasterModel olotmaster)
        //{
        //    try
        //    {
        //        string inputstr = JsonConvert.SerializeObject(olotmaster);
        //        var retval = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, "updatelot");
        //        return Ok(retval);
        //    }
        //    catch (Exception ex)
        //    {
        //        oCommonRepository.ErrorLog(ex);
        //        return BadRequest(new { message = ex.Message });
        //    }
        //}

        [Authorize]
        [HttpPost("Putlotmetafields")]
        public IActionResult Putlotmetafields([FromBody] List<lotmasterModel> olotmaster)
        {
            try
            {
                List<object> list = new List<object>();
                foreach (var item in olotmaster)
                {
                    string inputstr = JsonConvert.SerializeObject(item);

                    var retval = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, "updatelot");
                    list.Add(retval);

                }
                return Ok(list);

            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        }

        [Authorize]
        [HttpPost("Getlotmeta")]
        public IActionResult Getlotmeta([FromBody] lotmasterModel data)
        {
            string input = JsonConvert.SerializeObject(data);
            var list = CommonRepository.ExecuteSP_ReturnList2("splotmasterselect", input, "getlotbypdid");
            var lotdetails = JsonConvert.DeserializeObject<object>(list.ToString());
            JArray lotlist = JArray.Parse(lotdetails.ToString());
            var _list = new List<object>();
            foreach (var i in lotlist)
            {
                metadata lst = new metadata();
                if (i["lotmastermetafields"].ToString() != "" && i["lotmastermetafields"].ToString() != null)
                {
                    var metadetails = JsonConvert.DeserializeObject<object>(i["lotmastermetafields"].ToString());
                    JArray metalist = JArray.Parse(metadetails.ToString());
                    foreach (var j in metalist)
                    {
                        if (j["FieldName"].ToString() == "City")
                        {
                            lst.City = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "Company Name")
                        {
                            lst.CompanyName = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "Type")
                        {
                            lst.Type = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "Frequency")
                        {
                            lst.Frequency = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "State")
                        {
                            lst.State = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "Project ID")
                        {
                            lst.ProjectID = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "URL")
                        {
                            lst.URL = j["FieldValue"].ToString();
                        }
                        else if (j["FieldName"].ToString() == "Ranking")
                        {
                            lst.Ranking = j["FieldValue"].ToString();
                        }
                        if (lst.jobid == 0) lst.jobid = Convert.ToInt64(i["jobid"]);
                        if (lst.lotid == 0) lst.lotid = Convert.ToInt64(i["lotid"]);
                    }
                    _list.Add(lst);
                }
            }
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("InsertBidnumber")]
        public IActionResult InsertBidnumber([FromBody] bidnumberModel Bidnumberlist)
        {
            try
            {
                string inputstr = JsonConvert.SerializeObject(Bidnumberlist);
                var retval = CommonRepository.ExecuteSP_ReturnList2("spbidnumbermaster", inputstr, "insert");
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest(new { message = ex.Message });
            }
        } 
        public class metadata
        {
            public string CompanyName { get; set; }
            public string Type { get; set; }
            public string Frequency { get; set; }
            public string City { get; set; }
            public string ProjectID { get; set; }
            public string State { get; set; }
            public string URL { get; set; }
            public string Ranking { get; set; }
            public long lotid { get; set; }
            public long jobid { get; set; }
        }

        public class lotinfoexcellist
        {
            public string sno { get; set; }
            public string CompanyName { get; set; }
            public string Type { get; set; }
            public string Ranking { get; set; }
            public string Frequency { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string FollowUpDate { get; set; }
            public string Status { get; set; }
        }
    }
}