using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading.Tasks;
using Fast.Logic.Valuation;
using Fast.Shared;
using Fast.Shared.Logic.FileService;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; //requires Microsoft.AspNetCore.Mvc.NewtonsoftJson package
using Microsoft.AspNetCore.OData.Query;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[assembly: Parallelize]
namespace Test;

[TestClass]
public class Test1
{
    public static IConfiguration? Configuration { get; set; }
    static MockHostingEnvironment Env { get; set; } = new MockHostingEnvironment();

    //TestContext is required even though it isn't used
    //otherwise tests don't run; they silently fail
    [AssemblyInitialize()]
    public static void AssemblyInit(TestContext context)
    {
        ProgramShared.IsDevEnv = true;
        ArgumentNullException.ThrowIfNull(context);

        Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
        //env.ContentRootPath = context.TestRunResultsDirectory;
        Env.ContentRootPath = new DirectoryInfo(Directory.GetCurrentDirectory())?.FullName ?? "";
        ProgramShared.SetupDatabaseConnection();
    }

    [TestMethod]
    public void DeleteSharePointDirectory()
    {
        var config = new FileServiceConfig(Env.ContentRootPath);
        config.SharePoint.TenantId = "93e3e76b-c333-4adf-b4b2-4c1b7119c12f";
        config.SharePoint.ClientId = "0061481e-33a5-429b-aaba-b3d76687a497";
        config.SharePoint.ClientSecret = "2pT8Q~3iwCwzW4STRf5k4IP.1NX34fXMYkcIFcsn";
        var fileService = new SharePointFileService(config);
        fileService.DeleteDirectory("DealTemplates");
    }

    [TestMethod]
    public void UploadLocalFileToSharepoint()
    {
        var config = new FileServiceConfig(Env.ContentRootPath);
        config.SharePoint.TenantId = "93e3e76b-c333-4adf-b4b2-4c1b7119c12f";
        config.SharePoint.ClientId = "0061481e-33a5-429b-aaba-b3d76687a497";
        config.SharePoint.ClientSecret = "2pT8Q~3iwCwzW4STRf5k4IP.1NX34fXMYkcIFcsn";
        var fileService = new SharePointFileService(config);
        var fileName = "NAESBExhibitC.docx";
        var localFileBytes = File.ReadAllBytes(fileName); //default path is in Test/bin/debug/net folder
        fileService.WriteAllBytes("ContractTemplates", fileName, localFileBytes, false);
    }

    [TestMethod]
    public void AuthSecretGenerator()
    {
        RandomNumberGenerator cryptoRandomDataGenerator = RandomNumberGenerator.Create();
        byte[] buffer = new byte[16];
        cryptoRandomDataGenerator.GetBytes(buffer);
        string uniq = Convert.ToHexString(buffer);
        Assert.IsGreaterThan(0, uniq.Length);
    }

    [TestMethod]
    public async Task ValTest()
    {
        var valuater = new Valuater();
        var x = (await valuater.GetValuationValues("CRO2558")).ToList();
        var f = x.First();
        var p = f.CrudeRollPrice;
        Assert.AreNotEqual(0, p);
    }

    internal static ODataQueryOptions<T> GetOdataOptions<T>(string routeUrl)
    {
        string path = "../.vscode/settings.json";
        string settingsText = File.ReadAllText(path);
        var settings = JsonSerializer.Deserialize<Dictionary<string, object>>(settingsText);
        string? port = "";
        if (settings != null)
            port = settings["fast.module.name"].ToString();

        var baseOdataStr = "https://127.0.0.1:443" + port + @"/odata";
        var uri = new Uri($"{baseOdataStr}/{routeUrl}");
        var httpContext = new DefaultHttpContext();

        HttpRequest request = httpContext.Request;
        request.Method = "GET";
        request.Host = new HostString(uri.Host, uri.Port);
        request.Path = uri.LocalPath;
        request.QueryString = new QueryString(uri.Query);

        var edmModel = Fast.Web.Helper.GetCustomEdmModel();
        ODataQueryContext context = new(edmModel, typeof(T), new Microsoft.OData.UriParser.ODataPath());
        ODataQueryOptions<T> options = new(context, request);

        return options;
    }

    internal class MockHostingEnvironment : IHostEnvironment, IWebHostEnvironment
    {
        public string EnvironmentName { get; set; } = Environments.Production;

        public string ApplicationName { get; set; } = "";

        public string WebRootPath { get; set; } = "";

        public string ContentRootPath { get; set; } = "";

        public IFileProvider ContentRootFileProvider { get; set; } = new PhysicalFileProvider("/");
        public IFileProvider WebRootFileProvider { get; set; } = new PhysicalFileProvider("/");

        IFileProvider IHostEnvironment.ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    }
}
