using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace DEMO_FULL_CA_DOTNET_WEB.Controllers
{
    public class FileController : Controller
    {
        // GET: File
        //[HttpPost]
        public ActionResult Upload()
        {
            ViewBag.StatusResultUpload = "error";
            ViewBag.DescErrorUpload = "";
            ViewBag.FileName = "";
            try
            {
                if (Request.Files == null || Request.Files.Count == 0)
                {
                    ViewBag.DescErrorUpload = "Dữ liệu đẩy lên Empty";
                    return View();
                }
                //Chỉ tải lên 1 file
                HttpPostedFileBase file = Request.Files[0];
                var fileContent = Request.Files[0];

                if (fileContent == null || fileContent.ContentLength == 0)
                {
                    ViewBag.DescErrorUpload = "Dữ liệu đẩy lên Empty";
                    return View();
                }

                if (fileContent.ContentLength > 10 * 8388608)
                {
                    ViewBag.DescErrorUpload = "File cần có kích thước nhỏ hơn bằng 10 MB";
                    return View();
                }

                if (!"application/pdf".Equals(fileContent.ContentType) && !"application/octet".Equals(fileContent.ContentType))
                {
                    ViewBag.DescErrorUpload = "Cần chọn file PDF có phần mở rộng .pdf";
                    return View();
                }

                string fileName = fileContent.FileName;

                if (fileName == null || fileName.Length == 0
                        || fileName.ToLower().IndexOf(".pdf") == -1
                        || !fileName.ToLower().Substring(fileName.ToLower().IndexOf(".pdf")).Equals(".pdf"))
                {
                    ViewBag.DescErrorUpload = "Cần chọn file PDF có phần mở rộng .pdf";
                    return View();
                }

                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                //var fileName = Path.GetFileName(file);

                String name = System.Guid.NewGuid().ToString();
                String ext = "pdf";
                String filePath = Server.MapPath("~/upload");

                bool exists = System.IO.Directory.Exists(filePath);
                if (!exists)
                    System.IO.Directory.CreateDirectory(filePath);


                exists = System.IO.File.Exists(filePath + "/" + name + "." + ext);
                if (exists)
                {
                    int index = 1;
                    string name_2 = name + "_" + index;
                    string path_2 = filePath + "/" + name_2 + "." + ext;
                    while (System.IO.File.Exists(path_2))
                    {
                        index++;
                        name_2 = name + "_" + index;
                        path_2 = filePath + "/" + name_2 + "." + ext;
                    }
                    name = name_2;
                }

                string fileNameNew = name + "." + ext;

                var path = Path.Combine(Server.MapPath("~/upload"), fileNameNew);
                using (var fileStream = System.IO.File.Create(path))
                {
                    stream.CopyTo(fileStream);
                }

                ViewBag.StatusResultUpload = "success";
                ViewBag.FileName = fileNameNew;
            }
            catch (Exception)
            {
                ViewBag.DescErrorUpload = "Không ghi được File vào Folder Upload";
                return View();
            }
            return View();
        }
        public ActionResult Download()
        {
            ViewBag.statusResultDownloadFile = "error";
            ViewBag.descErrorDownloadFile = "";

            String fileName = Request.QueryString.Get("fileName");
            if (fileName == null || fileName.Trim().Length == 0)
            {
                ViewBag.descErrorDownloadFile = "FileName is empty";
                return View();
            }

            if (fileName.ToLower().IndexOf(".pdf") == -1
                    || !fileName.ToLower().Substring(fileName.ToLower().LastIndexOf(".pdf")).Equals(".pdf"))
            {
                ViewBag.descErrorDownloadFile = "Cần chọn file PDF có phần mở rộng .pdf";
                return View();
            }

            string pattern = @"[^-_.A-Za-z0-9]";
            Match m = Regex.Match(fileName, pattern, RegexOptions.IgnoreCase);
            if (m.Success)
            {
                ViewBag.descErrorHashFile = "FileName chứa ký tự đặc biệt";
                return View();
            }

            //Get the servers upload directory real path name
            String folderPath = Server.MapPath("~/upload/");
            String fileFullPath = folderPath + "/" + fileName;
            //create the upload folder if not exists
            //logger.info("fileFullPath: " + fileFullPath);
            bool exists = System.IO.File.Exists(fileFullPath);
            if (!exists)
            {
                ViewBag.descErrorHashFile = "File không tồn tại";
                return View();
            }
            try
            {
                FileInfo fileInfo = new FileInfo(fileFullPath);

                if (fileInfo.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Flush();
                    Response.TransmitFile(fileInfo.FullName);
                    Response.End();
                }
                else
                {
                    ViewBag.descErrorHashFile = "File không tồn tại";
                    return View();
                }
                
            }
            catch (Exception e)
            {
                ViewBag.descErrorHashFile = "Download File thất bại";
                return View();
            }

            ViewBag.statusResultDownloadFile = "success";

            return View();
        }
    }
}