using BrianMalingaPortfolio.Models;
using BrianMalingaPortfolio.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace BrianMalingaPortfolio.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        private static readonly string[] AllowedProjectExtensions =
        {
            ".zip",
            ".rar",
            ".7z",
            ".pdf",
            ".doc",
            ".docx",
            ".txt",
            ".cs",
            ".cshtml",
            ".html",
            ".css",
            ".js",
            ".json",
            ".sql",
            ".pbix",
            ".xlsx",
            ".xls",
            ".csv",
            ".ppt",
            ".pptx",
            ".exe"
        };

        public HomeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        public IActionResult Index()
        {
            var model = new HomeViewModel
            {
                Name = "Brian Malinga",

                Title = "Technology, Business & Project Professional",

                PortfolioProjectCount =
                    CountProjectFiles("portfolio-websites"),

                WebAppsProjectCount =
                    CountProjectFiles("web-apps"),

                DataAnalyticsProjectCount =
                    CountProjectFiles("data-analysis")
            };

            return View(model);
        }

        private int CountProjectFiles(string folderName)
        {
            string folder = Path.Combine(
                _environment.WebRootPath,
                "downloads",
                "projects",
                folderName
            );

            if (!Directory.Exists(folder))
            {
                return 0;
            }

            return Directory
                .GetFiles(folder)
                .Count(file =>
                    AllowedProjectExtensions.Contains(
                        Path.GetExtension(file),
                        StringComparer.OrdinalIgnoreCase
                    )
                );
        }



        public IActionResult PageNotFound(int statusCode = 404)
        {
            Response.StatusCode = statusCode;

            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
                }
            );
        }
    }
}