using EDAViewer.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Shared;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;

namespace EDAViewer.Controllers
{

    public class HomeController : Controller, IHomeController
    {

        private readonly Log _Log;
        private readonly AppSettings _AppSettings;
        private readonly IsEnvironment _IsEnvironment;
        private readonly Singleton.IBackground _Background;

        public HomeController(ILogger<HomeController> logger, IsEnvironment isEnvironment, Singleton.IBackground background, AppSettings appSettings)
        {
            _Log = new Log(logger);
            _Background = background;
            _AppSettings = appSettings;
            _IsEnvironment = isEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult Encode(string value = null)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(value))
                result = HttpUtility.UrlEncode(value);
            return Content(result, "text/plain");
        }

        public IActionResult Background(bool? message_clear = null, bool? exceptions_clear = null, bool? set_is_primary_instance = null, int? invoke_eda_dcp = null)
        {
            _Background.SendStatusOk();
            if (message_clear.HasValue && message_clear.Value)
                _Background.ClearMessage();
            if (exceptions_clear.HasValue && exceptions_clear.Value)
                _Background.Exceptions.Clear();
            if (set_is_primary_instance.HasValue)
            {
                if (set_is_primary_instance.Value)
                    _Background.SetIsPrimaryInstance();
                else
                    _Background.ClearIsPrimaryInstance();
            }
            string message;
            if (string.IsNullOrWhiteSpace(_Background.Message))
                message = "N/A";
            else
                message = _Background.Message;
            //Response.AppendToLog(_Background.Message);
            List<Exception> exceptions = new();
            foreach (Exception exception in _Background.Exceptions)
                exceptions.Add(exception);
            ViewBag.Message = message;
            ViewBag.Exceptions = exceptions;
            ViewBag.URLs = _AppSettings.URLs;
            ViewBag.Profile = _IsEnvironment.Profile;
            ViewBag.WorkingDirectory = _Background.WorkingDirectory;
            ViewBag.IsPrimaryInstance = _Background.IsPrimaryInstance();
            ViewBag.ExceptionsCount = string.Concat("Exception(s) - ", exceptions.Count);
            return View();
        }

        public ActionResult<IEnumerable<SelectListItem>> GetDirectoriesOrFiles(string path = null, bool? upDirectory = null, string filter = null)
        {
            List<SelectListItem> results = new();
            //System.Threading.Thread.Sleep(1500);
            //path = @"D:\Tmp";
            if (string.IsNullOrEmpty(path))
                path = string.Concat(@"\\", _AppSettings.Server, @"\EC_EDA");
            if (string.IsNullOrEmpty(filter))
                filter = "*";
            if (upDirectory.HasValue && upDirectory.Value && path.Contains('|'))
            {
                string[] segments = path.Split('|');
                path = segments[^1];
            }
            //System.IO.File.AppendAllText(string.Concat(@"\\", _AppSettings.Server, @"\EC_EDA\a.txt"), path);
            string gold = "Gold";
            if (System.IO.File.Exists(path))
            {
                string[] files = Directory.GetFiles(Path.GetDirectoryName(path), filter, SearchOption.TopDirectoryOnly);
                foreach (string item in files)
                    results.Add(new SelectListItem() { Value = item, Text = Path.GetFileName(item), Group = new SelectListGroup() { Name = "File(s)" } });
                if (results.Count > 1)
                    results.Insert(0, new SelectListItem() { Value = string.Empty, Text = string.Concat("Select - ", 0, " - ", files.Length) });
            }
            else if (Directory.Exists(path))
            {
                string[] files = Directory.GetFiles(path, filter, SearchOption.TopDirectoryOnly);
                string[] directories = Directory.GetDirectories(path, filter, SearchOption.TopDirectoryOnly).Where(l => Path.GetFileName(l) != gold).ToArray();
                for (short i = 0; i < short.MaxValue; i++)
                {
                    if (directories.Length != 1 || files.Length != 0)
                        break;
                    else
                    {
                        path = directories[0];
                        files = Directory.GetFiles(path, filter, SearchOption.TopDirectoryOnly);
                        directories = Directory.GetDirectories(path, filter, SearchOption.TopDirectoryOnly).Where(l => Path.GetFileName(l) != gold).ToArray();
                        if (directories.Length == 0 && files.Length == 0)
                        {
                            directories = new string[] { path };
                            break;
                        }
                    }
                }
                foreach (string item in directories)
                    results.Add(new SelectListItem() { Value = item, Text = Path.GetFileName(item), Group = new SelectListGroup() { Name = "Directorie(s)" } });
                foreach (string item in files)
                    results.Add(new SelectListItem() { Value = item, Text = Path.GetFileName(item), Group = new SelectListGroup() { Name = "File(s)" } });
                if (results.Count > 1)
                    results.Insert(0, new SelectListItem() { Value = string.Empty, Text = string.Concat("Select - ", directories.Length, " - ", files.Length) });
            }
            //System.IO.File.AppendAllText(string.Concat(@"\\", _AppSettings.Server, @"\EC_EDA\b.txt"), results.Count.ToString());
            if (!results.Any())
                results.Add(new SelectListItem() { Value = path, Text = string.Concat("Nothing Found *{", path, "}") });
            return results;
        }

        public IActionResult ViewEdaHtmlDiff(WithEnvironment withEnvironment = null)
        {
            if (withEnvironment is null)
                withEnvironment = new WithEnvironment();
            string path = string.Concat(@"\\", _AppSettings.Server, @"\EC_EDA");
            if (!Directory.Exists(path))
                path = @"C:\";
            EdaHtmlDiff model = new(withEnvironment, path);
            ViewBag.message = model.message;
            return View(model);
        }

    }

}
// dotnet publish --configuration Release --runtime win-x64 --verbosity normal --self-contained true -o "L:\net5.0\EDAViewer"
// dotnet publish --configuration Release --runtime win-x64 --verbosity normal --self-contained true -o "D:\net5.0\EDAViewer"
// dotnet publish --configuration Release --runtime win-x64 --verbosity normal --self-contained true -o "D:\.jenkins\publish\manual-Mesa-0\EDAViewer"
//http://eaf-dev.mes.infineon.com:8080/job/Mesa/buildWithParameters?token=DotnetRules&projectName=EDA%20Viewer
//http://eaf-prod.mes.infineon.com:8080/job/Mesa/buildWithParameters?token=DotnetRules&projectName=EDA%20Viewer
//sc create EDAViewer_5003 binPath="D:\.jenkins\publish\manual-Mesa-0\EDAViewer\EDA Viewer.exe"