using MarketData;
using MarketData.Utils;
using MarketDataServer.Authorization;
using Microsoft.AspNetCore.Mvc;
using LogLevel = MarketData.LogLevel;

namespace MarketDataServer.Controllers
{
  [ApiController]
  [Route("api/[controller]/[action]")]
  public class AuthorizationController : ControllerBase
  {
    [HttpGet(Name = "GetToken")]
    public String GetToken(String user, String password)
    {
      Profiler profiler = new Profiler();
      try
      {
        MDTrace.WriteLine(LogLevel.DEBUG,$"Start");
        if(null==user)return null;
        user=Authorizations.Xor(user,5);
        password=Authorizations.Xor(password,5);
        MDTrace.WriteLine(LogLevel.DEBUG,$"Login requested for user '{user}'");
        if(!Authorizations.GetInstance().IsValidUser(user, password))
        {
          MDTrace.WriteLine(LogLevel.DEBUG,$"User '{user}' is not authorized.");
          return null;
        }
        String accessToken= Authorizations.GetInstance().GetAuthenticationToken();
        MDTrace.WriteLine(LogLevel.DEBUG,$"Access token granted for user {user} : {accessToken}.");
        return accessToken;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,$"Exception:{exception.ToString()}");
        return null;
      }
      finally
      {
        MDTrace.WriteLine(LogLevel.DEBUG,$"Done, total took {profiler.End()} (ms)");
      }      
    }
  }
}
