using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Models.Configuration;

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

namespace WK_KLI_LAPS_Service.Controllers.Configuration.SmartChart
{
    [Route("api/[controller]")]
    [ApiController]
    public class SmartChartApiController : ControllerBase
    {
        CommonRepository oCommonRepository = new CommonRepository();
        private ISmartChartService _ISmartChartService;
        public SmartChartApiController(ISmartChartService SmartChartService)
        {
            _ISmartChartService = SmartChartService;
        }


        /// To get the active master table names
        [Authorize]
        [HttpGet("GetActiveMasterTables")]
        public IActionResult GetActiveMasterTables()
        {
            var _masterTableList = _ISmartChartService.GetActiveMasterTables();
            return Ok(_masterTableList);
        }

        [Authorize]

        [HttpGet("GetActiveFieldAlias")]
        public IActionResult GetActiveFieldAlias()
        {
            var _fieldAliasList = _ISmartChartService.GetActiveFieldAlias();
            return Ok(_fieldAliasList);
        }

        [Authorize]
        [HttpGet("GetFormConfigDashboardField/{id}")]
        public IActionResult GetFormConfigDashboardField(int id)
        {

            var formConfiglist = _ISmartChartService.GetFormConfigDashboardField(id);
            return Ok(formConfiglist);


        }

        /// To add the given mail template
        [AllowAnonymous]
        [HttpPost("add")]
        public IActionResult add([FromBody] smartChartModel osmartChartModel)
        {

            int retval = 0;

            retval = _ISmartChartService.Add(osmartChartModel);
            return Ok(retval);

        }

        //code to get smartchartconfig by smartchartconfigid
        [Authorize]
        [HttpPost("GetById")]
        public IActionResult getByID([FromBody] smartChartModel osmartChartModel)
        {

            var list = _ISmartChartService.getByID(osmartChartModel);
            return Ok(list);

        }

        //Code to update specific record
        [Authorize]
        [HttpPost("Update")]
        public IActionResult Update([FromBody] smartChartModel osmartChartModel)
        {
            int retval = 0;
            retval = _ISmartChartService.Edit(osmartChartModel);
            return Ok(retval);

        }


        [Authorize]
        [HttpGet("GetAllGivenMasterDetails/{tableid}")]
        public ActionResult GetAllGivenMasterDetails(string tableid)
        {
            var _list = _ISmartChartService.GetAllGivenMasterDetails(tableid);
            return Ok(_list);
        }

        /// Add Given dynamic Form data
        [Authorize]
        [HttpPost("addSmartChartData")]
        public IActionResult addSmartChartData()
        {
            int retval = 0;
            try
            {
                var httpRequest = HttpContext.Request.Form;
                string _fileNames = string.Empty;
                string _fieldName = string.Empty;
                // string txtfulltextfilename = "";
                if (Request.Form != null)
                {
                    Dictionary<string, string> dictValues = new Dictionary<string, string>();
                    Dictionary<string, string> result = new Dictionary<string, string>();
                    foreach (var key in Request.Form.Keys)
                    {
                        // dictValues.Add(key, Request.Form[key].ToString());
                        if (key.StartsWith("txtarea") || key.StartsWith("txt"))
                        {
                            dictValues.Add(key, Request.Form[key].ToString().Replace("'", "''''"));
                        }
                        else
                        {
                            dictValues.Add(key, Request.Form[key].ToString());
                        }
                    }
                    string tablename = Request.Form["tablename"].ToString();
                    string formName = Request.Form["smartchartid"].ToString();
                    string tranid = Request.Form["transactionid"].ToString();
                    dictValues.Add("createdon", "now()");

                    if (Request.Form.Files.Count > 0)
                    {
                        Dictionary<string, string> dictValues1 = getfiledetails(httpRequest);
                        result = dictValues.Concat(dictValues1).ToDictionary(e => e.Key, e => e.Value);

                    }
                    else
                    {
                        result = dictValues.ToDictionary(e => e.Key, e => e.Value);
                    }
                    string folderName = Request.Form["outlineconfigid"].ToString().Replace(" ", "").ToString().ToLower();
                    string subfoldername1 = Request.Form["outlineconfigdetailid"].ToString().Replace(" ", "").ToString().ToLower();
                    string subfoldername2 = "smartchartFormdocuments";
                    string webRootPath = oCommonRepository.GetServerPath(tranid, "serverinfo", true);
                    string newPath = "";//Path.Combine(webRootPath.ToString().ToLower(), folderName.ToString().ToLower(), subfoldername1.ToString().ToLower(), subfoldername2.ToString().ToLower());


                    string inputjson = JsonConvert.SerializeObject(result, Formatting.Indented);
                    //inputjson = inputjson.ToLower();
                    retval = _ISmartChartService.addSmartChartData(inputjson, formName, tablename);
                    if (Request.Form.Files.Count > 0)
                    {
                        string formConfigName = formName;
                        for (int i = 0; i < httpRequest.Files.Count; i++)
                        {
                            var file = Request.Form.Files[i];
                            var filefieldname = Request.Form.Files[i].Name;
                            if (file != null)
                            {
                                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                                //  dictValues.Add(filefieldname, fileName);
                                var extension = Path.GetExtension(fileName);
                                var size = file.Length;
                                string fullPath = "";
                                newPath = Path.Combine(webRootPath.ToString().ToLower(), folderName.ToString().ToLower(), subfoldername1.ToString().ToLower());
                                if (!Directory.Exists(newPath))
                                    Directory.CreateDirectory(newPath);
                                if (Directory.Exists(newPath))
                                {
                                    string formconfigPath = Path.Combine(newPath, subfoldername2.ToString().ToLower());
                                    if (!Directory.Exists(formconfigPath))
                                        Directory.CreateDirectory(formconfigPath);
                                    if (Directory.Exists(formconfigPath))
                                    {
                                        string formPath = Path.Combine(formconfigPath, retval.ToString(), "create");
                                        if (!Directory.Exists(formPath))
                                            Directory.CreateDirectory(formPath);
                                        if (Directory.Exists(formPath))
                                        {
                                            fullPath = Path.Combine(formPath, fileName.Replace("''", "'"));
                                            using (var stream = new FileStream(fullPath, FileMode.Create))
                                            {
                                                file.CopyTo(stream);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return Ok(retval);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                // return error message if there was an exception
                return BadRequest(new { message = ex.Message });
            }

        }

        public Dictionary<string, string> getfiledetails(IFormCollection httpRequest)
        {
            Dictionary<string, string> dictValues = new Dictionary<string, string>();
            string _fileNames = string.Empty;
            string _fieldName = string.Empty;
            string _fileSize = string.Empty;
            for (int i = 0; i < httpRequest.Files.Count; i++)
            {
                var file = Request.Form.Files[i];
                var fileSize = (Request.Form.Files[i].Length / 1024) + "KB";
                var filefieldname = Request.Form.Files[i].Name;
                //var _fileSize = (Request.Form.Files[i].Length / 1024).ToString() + "KB";
                //var _fileSize = "";
                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var data = Request.Form.Files[i].Name.Split('_');
                _fieldName = data[0].ToString();
                if (i > 0)
                {
                    var previousName = Request.Form.Files[i - 1].Name.Split('_');
                    var previousfilesize = Request.Form.Files[i - 1].Length;
                    if (previousName[0].ToString() == _fieldName)
                    {
                        var s = _fileNames.Split(';');
                        for (int k = 0; k < s.Count(); k++)
                        {
                            if (s[k] != "")
                            {
                                //if (fileName != s[k])
                                if (!s[k].Contains(fileName) && !_fileNames.Split(';').Contains(fileName))
                                {
                                    _fileNames = fileName + ';' + _fileNames;
                                    // _fileSize = previousfilesize.ToString() + ';' + fileSize;
                                    _fileSize = fileSize + ';' + _fileSize;
                                }
                            }
                        }
                    }
                    else
                    {
                        var nextData = Request.Form.Files[i - 1].Name.Split('_');
                        _fileNames = _fileNames.Remove(_fileNames.Length - 1);
                        dictValues.Add(nextData[0].ToString(), _fileNames.Trim());
                        dictValues.Add(nextData[0].ToString() + "size", _fileSize.ToString());
                        _fileNames = string.Empty;
                        if (fileName != string.Empty)
                        {
                            _fileNames = fileName + ';' + _fileNames;
                            _fileSize = fileSize + ';' + _fileSize;
                        }
                    }
                }
                else
                {
                    if (_fileNames != string.Empty)
                    {
                        var s = _fileNames.Split(';');
                        for (int k = 0; k < s.Count(); k++)
                        {
                            if (s[k] != "")
                            {
                                // if (fileName != s[k])
                                if (!s[k].Contains(fileName) && !_fileNames.Split(';').Contains(fileName))
                                {
                                    _fileNames = fileName + ';' + _fileNames;
                                    _fileSize = fileSize.ToString() + ';' + _fileSize;
                                }
                            }
                        }
                    }
                    else { _fileNames = fileName + ';' + _fileNames; _fileSize = fileSize + ';' + _fileSize; }
                }
                if (i == httpRequest.Files.Count - 1)
                {
                    if (httpRequest.Files.Count != 1)
                    {
                        var previousName = Request.Form.Files[i - 1].Name.Split('_');
                        if (previousName[0].ToString() == _fieldName)
                        {
                            _fileNames = _fileNames.Remove(_fileNames.Length - 1);
                            dictValues.Add(_fieldName, _fileNames.Trim());
                            dictValues.Add(_fieldName + "size", _fileSize.ToString());
                            _fileNames = string.Empty;

                        }
                        else
                        {
                            _fileNames = _fileNames.Remove(_fileNames.Length - 1);
                            dictValues.Add(_fieldName, _fileNames.Trim());
                            dictValues.Add(_fieldName + "size", _fileSize.ToString());
                            _fileNames = string.Empty;
                        }
                        if (fileName != string.Empty)
                        {
                            _fileNames = fileName + ';' + _fileNames;
                            _fileSize = fileSize + ';' + _fileSize;
                        }
                    }
                    else
                    {
                        _fileNames = _fileNames.Remove(_fileNames.Length - 1);
                        dictValues.Add(_fieldName, _fileNames.Trim());
                        dictValues.Add(_fieldName + "size", _fileSize.ToString());
                        _fileNames = string.Empty;
                    }
                }

            }
            return dictValues;
        }
        //get  all form document information
        [Authorize]
        [HttpPost("getAllSmartChartAnswercount")]
        public ActionResult getAllSmartChartAnswercount(viewSmartChartModel data)
        {
            try
            {
                string countval = _ISmartChartService.getAllSmartChartAnswercount(data);
                return Ok(new { count = countval });
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest("Not Able to get Form Data");
            }
        }

        //get all form document information
        [Authorize]
        [HttpPost("getAllSmartChartAnswerDetails")]
        public ActionResult getAllSmartChartAnswerDetails(viewSmartChartModel data)
        {
            try
            {
                var _list = _ISmartChartService.getAllSmartChartAnswerDetails(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest("Not Able to get Form Data");
            }
        }

        //get all form document information
        [Authorize]
        [HttpPost("getSmartChartAnswerRenderDetails")]
        public ActionResult getSmartChartAnswerRenderDetails(viewSmartChartModel data)
        {
            try
            {
                var _list = _ISmartChartService.getSmartChartAnswerRenderDetails(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
                return BadRequest("Not Able to get Form Data");
            }
        }

        [Authorize]
        [HttpPut("updateSmartChartData")]
        public IActionResult updateSmartChartData()
        {
            int retval = 0;
            try
            {
                var httpRequest = HttpContext.Request.Form;
                string _fileNames = string.Empty;
                string _fieldName = string.Empty;
                if (Request.Form != null)
                {
                    Dictionary<string, string> dictValues = new Dictionary<string, string>();
                    Dictionary<string, string> result = new Dictionary<string, string>();
                    foreach (var key in Request.Form.Keys)
                    {
                        if (key.StartsWith("txtarea") || key.StartsWith("txt"))
                        {
                            dictValues.Add(key, Request.Form[key].ToString().Replace("'", "''''"));
                        }
                        else
                        {
                            dictValues.Add(key, Request.Form[key].ToString());
                        }
                    }
                    string tablename = Request.Form["tablename"].ToString();
                    string formName = Request.Form["smartchartid"].ToString();
                    string tranid = Request.Form["transactionid"].ToString();
                    dictValues.Add("modifiedon", "now()");
                    if (Request.Form.Files.Count > 0)
                    {
                        Dictionary<string, string> dictValues1 = getfiledetails(httpRequest);
                        result = dictValues.Concat(dictValues1).ToDictionary(e => e.Key, e => e.Value);
                    }
                    else
                    {
                        result = dictValues.ToDictionary(e => e.Key, e => e.Value);
                    }
                    string inputjson = JsonConvert.SerializeObject(result, Formatting.Indented);
                    retval = _ISmartChartService.updateSmartChartData(inputjson, formName, tablename);
                    string folderName = Request.Form["outlineconfigid"].ToString().Replace(" ", "").ToString().ToLower();
                    string subfoldername1 = Request.Form["outlineconfigdetailid"].ToString().Replace(" ", "").ToString().ToLower();
                    string subfoldername2 = "smartchartFormdocuments";
                    string webRootPath = oCommonRepository.GetServerPath(tranid, "serverinfo", true);
                    string newPath = "";//Path.Combine(webRootPath.ToString().ToLower(), folderName.ToString().ToLower(), subfoldername1.ToString().ToLower(), subfoldername2.ToString().ToLower());

                    if (Request.Form.Files.Count > 0)
                    {
                        string formConfigName = formName;
                        newPath = Path.Combine(webRootPath.ToString().ToLower(), folderName.ToString().ToLower(), subfoldername1.ToString().ToLower());
                        string formconfigPath = Path.Combine(newPath, subfoldername2);
                        string formPath = Path.Combine(formconfigPath, retval.ToString(), "Edit");
                        int fileCount = 0;//Directory.GetFiles(formPath, "*.*", SearchOption.TopDirectoryOnly).Length;
                        if (!Directory.Exists(formPath))
                            Directory.CreateDirectory(formPath);
                        if (Directory.Exists(formPath))
                        {
                            fileCount = Directory.GetFiles(formPath, "*.*", SearchOption.TopDirectoryOnly).Length;
                        }
                        //ended 
                        for (int i = 0; i < httpRequest.Files.Count; i++)
                        {
                            var file = Request.Form.Files[i];
                            var filefieldname = Request.Form.Files[i].Name;
                            if (file != null)
                            {
                                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                                var extension = Path.GetExtension(fileName);
                                var size = file.Length;
                                string fullPath = "";
                                if (!Directory.Exists(newPath))
                                    Directory.CreateDirectory(newPath);
                                if (Directory.Exists(newPath))
                                {
                                    if (!Directory.Exists(formconfigPath))
                                        Directory.CreateDirectory(formconfigPath);
                                    if (Directory.Exists(formconfigPath))
                                    {
                                        if (!Directory.Exists(formPath))
                                            Directory.CreateDirectory(formPath);
                                        if (Directory.Exists(formPath))
                                        {
                                            if (fileCount > 0 && i == 0)
                                            {
                                                string newpath = Path.Combine(formPath, "v1");
                                                DirectoryInfo dinfo = new DirectoryInfo(formPath);
                                                DirectoryInfo latestdir = dinfo.GetDirectories().OrderByDescending(f => f.CreationTime).FirstOrDefault();
                                                if (latestdir != null)
                                                {
                                                    char cLastCharacter = latestdir.Name[latestdir.Name.Length - 1];
                                                    int k = 0;
                                                    bool bNum = int.TryParse(cLastCharacter.ToString(), out k);
                                                    if (bNum)
                                                    {
                                                        k = k + 1;
                                                        newpath = Path.Combine(formPath, "v" + k);
                                                    }
                                                    if (!Directory.Exists(newpath))
                                                    {
                                                        Directory.CreateDirectory(newpath);
                                                    }
                                                    foreach (var oldfile in new DirectoryInfo(formPath).GetFiles())
                                                    {
                                                        oldfile.MoveTo($@"{newpath}\{oldfile.Name}");
                                                    }

                                                }
                                                else
                                                {
                                                    if (!Directory.Exists(newpath))
                                                    {
                                                        Directory.CreateDirectory(newpath);
                                                    }
                                                    foreach (var oldfile in new DirectoryInfo(formPath).GetFiles())
                                                    {
                                                        oldfile.MoveTo($@"{newpath}\{oldfile.Name}");
                                                    }
                                                }

                                            }
                                            fullPath = Path.Combine(formPath, fileName.Replace("''", "'"));
                                            using (var stream = new FileStream(fullPath, FileMode.Create))
                                            {
                                                file.CopyTo(stream);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                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("deactiveSmartChartData")]
        public IActionResult deactiveSmartChartAnswerDetails(viewSmartChartModel data)
        {

            try
            {
                var retval = _ISmartChartService.deactiveSmartChartAnswerDetails(data);
                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("DownloadFileAsZip")]
        public IActionResult DownloadFormFileAsZip(dynamic fileData)
        {
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            string tranid = fileData["transactionid"].ToString();
            string folderName = fileData["outlineconfigid"].ToString();
            string subfoldername1 = fileData["outlineconfigdetailid"].ToString();
            string subfoldername2 = "smartchartFormdocuments";
            string id = fileData["id"].ToString();
            string webRootPath = oCommonRepository.GetServerPath(tranid, "serverinfo", true);


            string filePath = string.Empty;
            string zipFileName = string.Empty;
            //string folderPath = Path.Combine(contentRootPath, dbName, formConfigId.ToString());
            string folderPath = Path.Combine(webRootPath.ToString().ToLower(), folderName.ToString().ToLower(), subfoldername1.ToString().ToLower(), subfoldername2.ToString().ToLower(), id.ToString().ToLower());
            //Path.Combine(webRootPath, fileData["dbName"].Value.Replace(" ", "").ToString().ToLower(), folderName.ToLower(), fileData["formConfigId"].Value.ToString(), fileData["documentId"].Value.ToString());
            if (Directory.Exists(folderPath))
            {

                DirectoryInfo dinfo = new DirectoryInfo(folderPath);
                DirectoryInfo latestdir = dinfo.GetDirectories().OrderByDescending(f => f.CreationTime).FirstOrDefault();
                string finalDirName = new DirectoryInfo(latestdir.ToString()).Name;
                string fromPath = string.Empty;

                if (latestdir != null)
                {
                    if (finalDirName.Trim().ToLower() != "finaloutput")
                    {
                        fromPath = Path.Combine(folderPath, latestdir.Name.ToString());
                    }
                    else
                    {
                        DirectoryInfo secondLatestDir = dinfo.GetDirectories().Where(f => !f.Name.Equals(finalDirName)).OrderByDescending(f => f.CreationTime).FirstOrDefault();
                        if (secondLatestDir != null)
                        {
                            fromPath = Path.Combine(folderPath, secondLatestDir.Name.ToString());
                        }
                    }


                    zipFileName = "Smart Chart Answer" + "_" + fileData["transactionid"].Value.ToString() + "_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
                    //Create the Zip File.                   


                    string zipPath = Path.Combine(folderPath, zipFileName + ".zip");
                    //ZipFile.CreateFromDirectory(fromPath, zipPath, CompressionLevel.NoCompression, false);
                    using (ZipArchive newFile = ZipFile.Open(zipPath, ZipArchiveMode.Create))
                    {
                        foreach (string file in Directory.GetFiles(fromPath))
                        {
                            newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
                        }
                    }

                    filePath = zipPath;

                }
            }

            if (filePath != "" || filePath.Length > 0)
            {

                byte[] file = System.IO.File.ReadAllBytes(filePath);
                System.IO.File.Delete(filePath);
                return Ok(new { File = file });

            }
            else
            {
                return BadRequest(new { message = "File notfound" });
            }

            // return Ok();

        }

        [Authorize]
        [HttpGet("getEditorDisplayStatus/{smartchartconfigid}")]
        public ActionResult getEditorDisplayStatusByID(string smartchartconfigid)
        {
            var _list = _ISmartChartService.getEditorDisplayStatusByID(smartchartconfigid);
            return Ok(_list);
        }

        [Authorize]
        [HttpPost("GetAllSmartAnswers")]
        public ActionResult GetAllSmartAnswers(viewSmartChartModel data)
        {
            try
            {
                var _list = _ISmartChartService.getAllSmartChartAnswers(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }

        [Authorize]
        [HttpPost("GetAllSmartAnswersCont")]
        public ActionResult GetAllSmartAnswersCont(viewSmartChartModel data)
        {
            try
            {
                var _list = _ISmartChartService.getAllSmartChartAnswersCount(data);
                return Ok(_list);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }
        [HttpPut("updateAllSmartChartData")]
        public IActionResult updateAllSmartChartData()
        {
            int retval = 0;
            try
            {
                var httpRequest = HttpContext.Request.Form;
                if (Request.Form != null)
                {
                    string result = Request.Form["input"].ToString();

                    //// string inputjson = JsonConvert.SerializeObject(result, Formatting.Indented);
                    retval = _ISmartChartService.updateAllSmartChartData(result);

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

        }

    }
}
