using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Principal;
using System.Threading.Tasks;
using WK_KLI_LAPS_Service.App_Data;

namespace WK_KLI_LAPS_Service.Controllers.Reports
{
    [EnableCors("CorsPolicy")]
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class ReportApiController : ControllerBase
    {
        //private IReportService _Reportservices;
        //public ReportApiController(IReportService reportservices)
        //{
        //    _Reportservices = reportservices;
        //}
        ReportServices oReportService = new ReportServices();

        [Authorize]
        [HttpPost("GetVlexreportdata")]
        //Code to retrieve all data
        public IActionResult GetVlexreportdata([FromBody] reportModel data)
        {
            var _list = oReportService.GetVlexreportdatagrid(data, "getall");
            var _statuspiechart = oReportService.GetVlexreportdata(data, "statuspiechart");
            var _jobcountpiechart = oReportService.GetVlexreportdata(data, "jobcountpiechart");
            return Ok(new
            {
                joblist = _list,
                jobstatus = _statuspiechart,
                monthwisejob = _jobcountpiechart
            });
        }

        [Authorize]
        [HttpPost("GetJobstatusReport")]
        //Code to retrieve all data
        public IActionResult GetJobstatusReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetJobstatusReport(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetJobcreationReport")]
        //Code to retrieve all data
        public IActionResult GetJobcreationReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetJobcreationReport(data);
            return Ok(_list);
        }



        [Authorize]
        [HttpPost("GetProductionDashboardStagewiseReport")]
        //Code to retrieve all data
        public IActionResult GetProductionDashboardStagewiseReport([FromBody] reportModel data)
        {
            var _list = oReportService.GeGetProductionDashboardStagewiseReport(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetUserwiseProductionLogReport")]
        //Code to retrieve all data
        public IActionResult GetUserwiseProductionLogReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetUserwiseProductionLogReport(data);
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("GetProductionReport")]
        //Code to retrieve all data
        public IActionResult GetProductionReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetProductionReport(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetProcessWiseProductionReport")]
        //Code to retrieve all data
        public IActionResult GetProcessWiseProductionReport([FromBody] reportModel data)
        {
            if (data.mode_report == "process")
            {
                var _list = oReportService.GetProcessWiseProductionReport(data);
                return Ok(_list);
            }
            else if (data.mode_report == "dashboard_old")
            {
                var totalcout = oReportService.GetDashboardTotalcount(data);
                var reportlst = oReportService.GetProcessWiseProductionReport(data);
                return Ok(new
                {
                    totalcout = totalcout,
                    reportlst = reportlst,
                });
            }
            else if (data.mode_report == "dashboard")
            {
                /**Overall data**/
                /*
                var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                var runtimedashboardlst = oReportService.GetRuntimeDashboardReport(data);
                data.p_stagename = "Web Check,Bid Entry,FPR";
                var runtimehourlylst = oReportService.GetRuntimHourlyProjecHealth(data);
                data.p_stagename = "Web Check,Bid Entry,FPR";
                var wipchartlst = oReportService.GetRuntimHourlyProjecHealth_Wip(data);
                return Ok(new
                {
                    runtimeprocesslst = runtimeprocesslst,
                    runtimedashboardlst = runtimedashboardlst,
                    runtimehourlylst = runtimehourlylst,
                    wipchartlst = wipchartlst
                });
                */
                /**tab wise data**/
                //if (data.tab_num == 1)
                //{
                //    var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                //    var runtimedashboardlst = oReportService.GetRuntimeDashboardReport(data);
                //    data.p_stagename = "Web Check,Bid Entry,FPR";
                //    var runtimehourlylst = oReportService.GetRuntimHourlyProjecHealth(data);
                //    return Ok(new
                //    {
                //        runtimeprocesslst = runtimeprocesslst,
                //        runtimedashboardlst = runtimedashboardlst,
                //        runtimehourlylst = runtimehourlylst
                //    });
                //}
                //if (data.tab_num == 2)
                //{
                //    var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                //    var runtimedashboardlst = oReportService.GetRuntimeDashboardReport(data);
                //    return Ok(new
                //    {
                //        runtimeprocesslst = runtimeprocesslst,
                //        runtimedashboardlst = runtimedashboardlst,
                //    });
                //}
                //if (data.tab_num == 4)
                //{
                //    data.p_stagename = "Web Check,Bid Entry,FPR";
                //    var wipchartlst = oReportService.GetRuntimHourlyProjecHealth_Wip(data);
                //    return Ok(new
                //    {
                //        wipchartlst = wipchartlst
                //    });
                //}
                if (data.tab_num == 1)
                {
                    data.p_stagename = "Web Check";
                    var runtimehourlylst = oReportService.GetRuntimHourlyProjecHealth(data);
                    return Ok(new
                    {
                        runtimehourlylst_WC = runtimehourlylst
                    });

                }
                else if (data.tab_num == 2)
                {
                    data.p_stagename = "Bid Entry";
                    var runtimehourlylst = oReportService.GetRuntimHourlyProjecHealth(data);
                    return Ok(new
                    {
                        runtimehourlylst_BE = runtimehourlylst
                    });

                }
                else if (data.tab_num == 3)
                {
                    data.p_stagename = "FPR";
                    var runtimehourlylst = oReportService.GetRuntimHourlyProjecHealth(data);
                    return Ok(new
                    {
                        runtimehourlylst_FPR = runtimehourlylst
                    });

                }
                else if (data.tab_num == 4)
                {
                    var runtimedashboardlst = oReportService.GetRuntimeDashboardReport(data);
                    return Ok(new
                    {
                        runtimedashboardlst = runtimedashboardlst
                    });

                }
                else if (data.tab_num == 5)
                {
                    data.p_stagename = "Web Check";
                    var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                    return Ok(new
                    {
                        runtimeprocesslst = runtimeprocesslst
                    });

                }
                else if (data.tab_num == 6)
                {
                    data.p_stagename = "FPR";
                    var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                    return Ok(new
                    {
                        runtimeprocesslst = runtimeprocesslst
                    });

                }
                else if (data.tab_num == 7)
                {
                    data.p_stagename = "Bid Entry,QA";
                    var runtimeprocesslst = oReportService.GetRuntimeProcesswiseReport(data);
                    return Ok(new
                    {
                        runtimeprocesslst = runtimeprocesslst
                    });

                }
                else if (data.tab_num == 8)
                {
                    data.p_stagename = "Web Check";
                    var _list = oReportService.Getruntimeuserperformancereport(data);

                    return Ok(_list);

                }
                else if (data.tab_num == 9)
                {
                    data.p_stagename = "Bid Entry";
                    var _list = oReportService.Getruntimeuserperformancereport(data);

                    return Ok(_list);
                }
                else if (data.tab_num == 10)
                {
                    data.p_stagename = "FPR";
                    var _list = oReportService.Getruntimeuserperformancereport(data);

                    return Ok(_list);
                }
                else if (data.tab_num == 11)
                {
                    data.p_stagename = "Web Check";
                    var wipchartlst = oReportService.GetRuntimHourlyProjecHealth_Wip(data);
                    return Ok(new
                    {
                        wipchartlst = wipchartlst
                    });

                }
                else if (data.tab_num == 12)
                {
                    data.p_stagename = "Bid Entry";
                    var wipchartlst = oReportService.GetRuntimHourlyProjecHealth_Wip(data);
                    return Ok(new
                    {
                        wipchartlst = wipchartlst
                    });

                }
                else if (data.tab_num == 13)
                {
                    data.p_stagename = "FPR";
                    var wipchartlst = oReportService.GetRuntimHourlyProjecHealth_Wip(data);
                    return Ok(new
                    {
                        wipchartlst = wipchartlst
                    });

                }

                return Ok("No Condition Matches");
            }
            else
            {
                return BadRequest();
            }
        }


        [Authorize]
        [HttpPost("GetUserwiseProductionReport")]
        //Code to retrieve all data
        public IActionResult GetUserwiseProductionReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetUserwiseProductionReport(data);
            return Ok(_list);
        }
        [Authorize]
        [HttpPost("Getruntimeuserperformancereport")]
        //Code to retrieve all data
        public IActionResult Getruntimeuserperformancereport([FromBody] reportModel data)
        {
            var _list = oReportService.Getruntimeuserperformancereport(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetJobTitle")]
        //Code to retrieve all data
        public IActionResult GetJobTitle([FromBody] reportModel data)
        {
            var _list = oReportService.GetJobTitle(data);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetRecordErrorReport")]
        public IActionResult GetRecordErrorReport([FromBody] reportModel data)
        {
            var _list = oReportService.GetRecordErrorReport(data);
            return Ok(_list);
        }
        [HttpPost("Recorderrorfile_download")]
        public async Task<IActionResult> Recorderrorfile_download(string projecdefid, string path)
        {
            string error = string.Empty;
            byte[] file = null;
            using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(projecdefid))
            {
                WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    System.Console.WriteLine(useri.Name);
                    var data = new
                    {
                        transactionid = projecdefid,
                        lotid = 0,
                        option = "serverinfo_projid"
                    };
                    string serverpath = FormatPath(path);
                    if (string.IsNullOrEmpty(error))
                    {
                        if (!System.IO.File.Exists(serverpath)) error = "File does not exists";
                        if (string.IsNullOrEmpty(error)) file = System.IO.File.ReadAllBytes(serverpath);
                    }
                });
                if (!string.IsNullOrEmpty(error))
                {
                    return BadRequest(new { message = error });
                }
                return Ok(new
                {
                    file_ = file
                });
            }
        }
        [AllowAnonymous]
        [HttpGet("Image_download")]
        public async Task<IActionResult> Image_download(string projecdefid, string path, string filename)
        {
            try
            {
                string error = string.Empty;
                var memory = new MemoryStream();

                using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission(projecdefid))
                {
                    WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();

                    await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
                    {
                        WindowsIdentity useri = WindowsIdentity.GetCurrent();
                        System.Console.WriteLine(useri.Name);
                        var data = new
                        {
                            transactionid = projecdefid,
                            lotid = 0,
                            option = "serverinfo_projid"
                        };

                        string serverpath = FormatPath(path);

                        using (var stream = new FileStream(path, FileMode.Open))
                        {
                            await stream.CopyToAsync(memory);
                        }
                    });

                }

                memory.Position = 0;
                var ext = Path.GetExtension(path).ToLowerInvariant();
                return File(memory, GetMimetype()[ext], filename);
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }
        }
        private Dictionary<string, string> GetMimetype()
        {
            return new Dictionary<string, string>
            {
                {".txt","text/plain"},
                {".pdf","application/pdf"},
                {".doc","application/vnd.ms-word"},
                {".docx","application/vnd.ms-word"},
                {".xls","application/vnd.ms-excel"},
                {".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
                {".png","image/png"},
                {".jpg","image/jpeg"},
                {".jpeg","image/jpeg"},
                {".gif","image/gif"},
                {".csv","image/csv"},

            };
        }
        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);
        }
        [HttpPost("GetAnswerData")]
        public IActionResult GetAnswerData([FromBody] texttelescopemodel data)
        {
            try
            {
                var _list = oReportService.GetAnswerData(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }
        [HttpGet("Getloball")]
        public IActionResult Getloball()
        {
            var _list = oReportService.Getloball();
            return Ok(_list);
        }
        [Authorize]
        [HttpGet("Getloginoutuser/{mode}")]
        public IActionResult Getloginoutuser(string mode)
        {
            var _list = oReportService.Getloginoutuser(mode);
            return Ok(_list);
        }
        public class texttelescopemodel
        {
            public Int64 lobid { get; set; }
            public string startdate { get; set; }
            public string enddate { get; set; }
        }
        public class reportModel
        {
            public long p_projectdefinitionid { get; set; }
            public string p_startdate { get; set; }
            public string p_enddate { get; set; }
            public long p_jobid { get; set; }
            public string mode_report { get; set; }
            public long p_interval { get; set; }
            public string p_stagename { get; set; }
            public string multipleprojectid_p { get; set; }
            public long p_isarchive { get; set; }
            public int tab_num { get; set; }
            public Boolean isnormaluser { get; set; }
            public string p_userid { get; set; }
        }
    }

}
