using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Nop.Plugin.SigmaSolve.StyleEditor.Domain;
using Nop.Plugin.SigmaSolve.StyleEditor.Models;
using System.Xml;
using CreateMSBuildProject;
using Nop.Web.Framework.Mvc.Filters;
using Nop.Web.Framework;
using Microsoft.AspNetCore.Mvc;
using Nop.Web.Framework.Controllers;
using Nop.Core.Data;
using Nop.Web.Framework.Themes;

namespace Nop.Plugin.SigmaSolve.StyleEditor.Controllers
{
    [AuthorizeAdmin]
    [Area(AreaNames.Admin)]
    public class StyleEditorController : BasePluginController
    {

        private readonly IRepository<StyleEditorRecord> _styleEditorRecordsRepository;
        private readonly IThemeContext _themeContext;
        private readonly string _projectMainPath;
        private readonly string _projectNopWebPath;
        private readonly string _projectPluginPath;
        private readonly string _projectThemePath;
        // private readonly IStylesEditor _stylesEditor;
        // private readonly ISiteThemeService _siteThemeService;
        // GET: StyleEditor

        public StyleEditorController(IThemeContext themeContext, IRepository<StyleEditorRecord> styleEditorRecordsRepository)
        {
            this._themeContext = themeContext;
            this._styleEditorRecordsRepository = styleEditorRecordsRepository;
            _projectMainPath = AppDomain.CurrentDomain.BaseDirectory.ToLower();
            _projectMainPath = _projectMainPath.Replace("\\nop.web", "");
            _projectMainPath = _projectMainPath.Replace("\\presentation", "");
            _projectNopWebPath = AppDomain.CurrentDomain.BaseDirectory.ToLower();
            _projectPluginPath = _projectMainPath + "plugins\\";
            _projectThemePath = _projectNopWebPath + "themes\\";

            _projectMainPath = AppDomain.CurrentDomain.BaseDirectory.ToLower().Split("presentation")[0];
            _projectNopWebPath = AppDomain.CurrentDomain.BaseDirectory.ToLower().Split("bin")[0];
            _projectPluginPath = _projectMainPath + "plugins\\";
            _projectThemePath = _projectNopWebPath + "themes\\";
            //   this._workingContext = workingContext;
            //   _extensionManager = extensionManager;
            //   _stylesEditor = stylesEditor;
            //  _siteThemeService = siteThemeService;
        }
        public ActionResult Index()
        {
            StyleEditorMainModel model = new StyleEditorMainModel();
            return View("~/Plugins/SigmaSolve.StyleEditor/Views/StyleEditor/Index.cshtml", model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult SaveFileContent(StyleEditorMainModel model)
        {
            try
            {
                var data = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == model.FolderPath.Replace(_projectMainPath, "src\\")).OrderByDescending(x => x.Id).FirstOrDefault();
                StyleEditorRecord record = new StyleEditorRecord();
                int version = 1;
                if (data != null)
                {
                    version = data.VersionNumber + 1;
                }
                record.FileContent = System.IO.File.ReadAllText(model.FolderPath);
                record.FilePath = model.FolderPath.Replace(_projectMainPath, "src\\");
                string fileToUpdate = GetPathToUpdateFile(model.FolderPath);
                record.VersionNumber = version;
                record.CreatedDate = System.DateTime.Now;
                _styleEditorRecordsRepository.Insert(record);
                var records = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == model.FolderPath.Replace(_projectMainPath, "src\\")).OrderByDescending(x => x.Id).ToList();
                if (records.Count > 10)
                {
                    records = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == model.FolderPath.Replace(_projectMainPath, "src\\")).OrderByDescending(x => x.Id).Skip(10).ToList();
                    _styleEditorRecordsRepository.Delete(records);
                }
                System.IO.File.WriteAllText(model.FolderPath, model.FileContant);
                if (!string.IsNullOrWhiteSpace(fileToUpdate))
                {
                    System.IO.File.WriteAllText(fileToUpdate, model.FileContant);
                }
            }
            catch (Exception e)
            {

            }
            model.StyleEditors = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == model.FolderPath.Replace(_projectMainPath, "src\\")).ToList().Select(x => new StyleEditorModel
            {
                Id = x.Id,
                FileContent = "",
                FilePath = x.FilePath,
                CreatedDate = x.CreatedDate.ToString("MM/dd/yyyy hh:mm tt"),
                VersionNumber = x.VersionNumber
            }).ToList();
            return Json(model);
        }
        [HttpGet]
        public JsonResult GetParentNode()
        {
            // _themeContext.WorkingThemeName
            var folderPath = _projectThemePath + _themeContext.WorkingThemeName + "\\";
            List<ZTreeModel> zTreeModels = new List<ZTreeModel>();
            ZTreeModel zTreeModel = new ZTreeModel();
            zTreeModel.name = _themeContext.WorkingThemeName;
            // zTreeModel.name = "";
            zTreeModel.open = false;
            zTreeModel.FolderPath = folderPath;
            zTreeModel.children = null;
            zTreeModel.isParent = true;
            zTreeModels.Add(zTreeModel);
            return Json(zTreeModels);
        }
        public string GetPathToUpdateFile(string currentFilePath)
        {
            if (currentFilePath == null)
                return "";
            currentFilePath = currentFilePath.ToLower();
            if (currentFilePath.Contains("\\src\\plugins"))
            {
                string tempCurrentFilePath = currentFilePath.Replace(_projectMainPath, "");
                var temp = tempCurrentFilePath.Split(new string[] { "\\" }, StringSplitOptions.None);
                //getting plugin folder name
                string pluginFolderName = temp[1];
                string pluginProjectFilePath = Directory.GetFiles(_projectPluginPath + pluginFolderName, "*.csproj", SearchOption.TopDirectoryOnly).FirstOrDefault();
                string pluginOutputPath = FindApplicationOutPutPath(pluginProjectFilePath);
                string fileToUpdate = currentFilePath.Replace(_projectPluginPath + pluginFolderName + "\\", pluginOutputPath).ToLower();
                return fileToUpdate;
            }
            return "";
        }
        public string FindApplicationOutPutPath(string pluginProjectFilePath)
        {
            CSProj temp = new CSProj(pluginProjectFilePath);
            var outPutPath = temp.OutputPath;
            var fullPath = outPutPath.ToLower().Replace("..\\..\\presentation\\nop.web", _projectMainPath + "presentation\\nop.web");
            return fullPath;
        }
        [HttpGet]
        public JsonResult GetParentNodeChecked()
        {
            List<ZTreeModel> zTreeModels = new List<ZTreeModel>();
            ZTreeModel zTreeModel = new ZTreeModel();
            zTreeModel.name = "src";
            zTreeModel.open = false;
            zTreeModel.FolderPath = _projectMainPath;
            zTreeModel.children = null;
            zTreeModel.isParent = true;
            zTreeModels.Add(zTreeModel);
            return Json(zTreeModels);
        }
        [HttpGet]
        public JsonResult GetChildNode(string folderPath)
        {
            // folder path will be Themes/SubFolder/

            // var stylePath = AppDomain.CurrentDomain.BaseDirectory + folderPath;
            string[] folders = Directory.GetDirectories(folderPath);
            string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly).Where(x => x.EndsWith(".css") || x.EndsWith(".cshtml") || x.EndsWith(".js")).ToArray();
            List<ZTreeModel> zTreeModels = new List<ZTreeModel>();
            foreach (var folder in folders)
            {
                var str = folder.Split("\\");
                if (str.Last().ToLower().Contains("content") || str.Last().ToLower().Contains("presentation") || str.Last().ToLower().Contains("nop.web") || str.Last().ToLower().Contains("wwwroot") || str.Last().ToLower().Contains("css")|| str.Last().ToLower().Contains("admin"))
                {
                ZTreeModel zTreeModel = new ZTreeModel();
                zTreeModel.name = Path.GetFileName(folder);
                zTreeModel.FolderPath = folder;
                zTreeModel.open = false;
                zTreeModel.children = null;
                zTreeModel.isParent = true;
                zTreeModels.Add(zTreeModel);
                }
            }

            foreach (string file in files)
            { 
                if (file.ToLower().Contains(".css"))
                {
                    ZTreeModel zTreeModel = new ZTreeModel();
                    zTreeModel.name = Path.GetFileName(file);
                    zTreeModel.FolderPath = file;
                    zTreeModel.open = false;
                    zTreeModel.children = null;
                    zTreeModel.isParent = false;
                    zTreeModels.Add(zTreeModel);
                }
            }
            return Json(zTreeModels);
        }
        [HttpGet]
        public JsonResult GetFileContant(string folderPath)
        {
            StyleEditorMainModel model = new StyleEditorMainModel();
            if (System.IO.File.Exists(folderPath))
            {
                model.FileContant = System.IO.File.ReadAllText(folderPath);
                model.FolderPath = folderPath;
            }
            model.StyleEditors = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == folderPath.Replace(_projectMainPath, "src\\")).ToList().Select(x => new StyleEditorModel
            {
                Id = x.Id,
                FileContent = "",
                FilePath = x.FilePath,
                CreatedDate = x.CreatedDate.ToString("MM/dd/yyyy hh:mm tt"),
                VersionNumber = x.VersionNumber
            }).ToList();
            //var jsonResult = Json(model, JsonRequestBehavior.AllowGet);
            //jsonResult.MaxJsonLength = int.MaxValue;
            //return jsonResult;
            return Json(model);
        }
        [HttpPost]
        public JsonResult BindVersionFileContant(int id)
        {
            StyleEditorMainModel model = new StyleEditorMainModel();
            var data = _styleEditorRecordsRepository.GetById(Convert.ToInt32(id));
            if (data != null)
            {
                model.FileContant = data.FileContent;
                model.FolderPath = data.FilePath;
            }
            return Json(model);
        }

        [HttpPost]
        public JsonResult ClearAllVersions()
        {
            var data = _styleEditorRecordsRepository.Table.ToList();
            _styleEditorRecordsRepository.Delete(data);
            return Json("");
        }

        [HttpPost]
        public JsonResult ClearAllVersionsAForCurrentFile(string folderPath)
        {
            var data = _styleEditorRecordsRepository.Table.Where(x => x.FilePath == folderPath.Replace(_projectMainPath, "src\\")).ToList();
            _styleEditorRecordsRepository.Delete(data);
            return Json("");
        }


    }
}