using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using FMSAdmin.Data;
using FMSAdmin.Helpers;
using System.Collections;
using System.Text.RegularExpressions;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Models.Formula;
using FMSAdmin.Helpers.Formula;
using FMSAdmin.Services;
using System.IO;
using OfficeOpenXml;
using System.Data;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;

namespace FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class FileDownloadController : Controller {
        private readonly ILogger<FileDownloadController> _logger;
        private readonly StorageHelper _storage;

        public FileDownloadController(
            ILogger<FileDownloadController> logger,
            StorageHelper storage
            ) {
            _logger = logger;
            _storage = storage;
        }
        [AllowAnonymous]
        [HttpGet("DownloadFile")]
        public IActionResult DownloadFile(String filePath, String fileName) {
            try {
                return File(_storage.GetFileStream(filePath), "application/octet-stream", fileName);
            } catch (Exception ex) {
                _logger.LogError(ex.ToString());
                return Content("<html><head><meta charset='UTF-8'></head><body><script>alert('파일을 찾을 수 없습니다.');window.close();</script></body></html>", "text/html");
            }
        }

        [AllowAnonymous]
        [HttpGet("PDFViewer/{fileName}")]
        public IActionResult PDFViewer(String filePath, String fileName) {
            try {
                Response.Headers.Add("Content-Disposition", "inline;filename*=UTF-8'" + Uri.EscapeDataString(fileName));
                Response.Headers.Add("X-Content-Type-Options", "nosniff");
                Response.Headers.Add("filename", WebUtility.UrlEncode("anvd"));

                return File(System.IO.File.ReadAllBytes(_storage.GetLocalPath(filePath)), "application/pdf");
            } catch (Exception ex) {
                _logger.LogError(ex.ToString());
                return Content("<html><head><meta charset='UTF-8'></head><body><script>alert('파일을 찾을 수 없습니다.');window.close();</script></body></html>", "text/html");
            }
        }
    }
}
