using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
using MarketData;
using MarketData.Configuration;
using MarketData.Utils;
using Microsoft.AspNetCore.Mvc;
using MarketDataServer.Authorization;

namespace MarketDataServer
{
  class Program
  {
    static void Main(string[] args)
    {
      String logFileName="marketdataserver";
      Authorizations.GetInstance().IsEnabled=false;
      WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
      GlobalConfig.Instance.Configuration = builder.Configuration; 
      String baseAddress = GlobalConfig.Instance.Configuration["server_address"];
      CreateLogging(logFileName);

      MDTrace.WriteLine(MarketData.LogLevel.DEBUG,$"Server Address:{baseAddress}");

      builder.Services.AddControllers().AddJsonOptions(options =>
      {
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
        options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.WriteAsString;
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));

      });

      builder.Services.AddEndpointsApiExplorer();
      builder.Services.AddSwaggerGen( config =>
      {
        config.ResolveConflictingActions (apiDescriptions => apiDescriptions.First ());
      });

      builder.Services.AddCors(options =>
      {
      options.AddPolicy("corsPolicy",
          builder =>
          {
              builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowedToAllowWildcardSubdomains();
          });
      });

      WebApplication webApplication = builder.Build();
      webApplication.UseCors("corsPolicy");

        // Configure the HTTP request pipeline.
      if (webApplication.Environment.IsDevelopment()||webApplication.Environment.IsProduction() )
      {
          webApplication.UseSwagger();
          webApplication.UseSwaggerUI();
      }

      webApplication.UseHttpsRedirection();
      webApplication.UseAuthorization();
      webApplication.MapControllers();
      webApplication.MapControllerRoute(name: "default",pattern: "api/{controller}/{action}/{id?}");
      webApplication.Run(baseAddress);  
    }

    private static bool CreateLogging(String task)
    {
      if(String.IsNullOrEmpty(task))return false;
      task=task.ToLower();
      MDTrace.LogLevel = MarketData.LogLevel.DEBUG;
      String logFolder = "/logs";
      DateTime currentDate=DateTime.Now;
      String strLogFile = "marketdata_" + task + ".log";
      String currentWorkingDirectory = Directory.GetCurrentDirectory();
      Console.WriteLine($"Current directory is {currentWorkingDirectory}");
      Utility.EnsureLogFolder(currentWorkingDirectory+logFolder);
      Utility.ExpireLogs(currentWorkingDirectory+logFolder,1);
      Trace.Listeners.Remove("Default");
      Console.WriteLine($"Adding Trace Listener :{currentWorkingDirectory+logFolder+"/"+strLogFile}");
      Trace.Listeners.Add(new TextWriterTraceListener(currentWorkingDirectory+logFolder+"/"+strLogFile));
      MDTrace.WriteLine($"Trace Listener added.");
      Utility.ShowLogs(currentWorkingDirectory + logFolder);
      return true;
    }  
  }
}

