using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Helpers;

namespace Siger.ApiCommon.Utilities
{
    public static class FileSystem
    {
        public static IApplicationBuilder RegisterFileSystem(this IApplicationBuilder app)
        {
            var rootFolder = FileSystemHelper.GetPhysicalFolders( FileSystemHelper.CommonFileSetting.PhysicalFolder);

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(rootFolder),
                RequestPath = $"/{FileSystemHelper.CommonFileSetting.RequestPath}"
            });

            return app;
        }

        public static IConfigurationBuilder RegisterOcelotSetting(this IConfigurationBuilder app)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Setting", "OcelotSetting.json");
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("can not found OcelotSetting.json");
            }

            app.AddJsonFile(path);

            return app;
        }

        public static IApplicationBuilder RegisterDownSetting(this IApplicationBuilder app)
        {
            
            var rootFolder = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.RootPath, CommonConst.DownloadProgramZIPFilePath);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(rootFolder),
                RequestPath = $"/{"Files"}"
            });

            return app;
        }
    }
}
