using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarketDataServer.Authorization
{
  public class Authorizations
  {
    private Dictionary<String, String> authorizationDictionary = null;
    private List<String> validUsers = null;
    private static Authorizations authorizations = null;
    private bool isEnabled=true;
    private Authorizations()
    {
      validUsers = new List<String>();
      authorizationDictionary=new Dictionary<String,String>();
      validUsers.Add("sean");
    }
    public static Authorizations GetInstance()
    {
      lock (typeof(Authorizations))
      {
        if (null == authorizations) authorizations = new Authorizations();
      }
      return authorizations;
    }
    public bool IsEnabled
    {
      get{return isEnabled;}
      set{isEnabled=value;}
    }
    public bool IsAuthorized(String token)
    {
      lock (this)
      {
        if(!IsEnabled)return true;
        return authorizationDictionary.ContainsKey(token);
      }
    }
    public String GetAuthenticationToken()
    {
      lock (this)
      {
        String token = Guid.NewGuid().ToString();
        authorizationDictionary.Add(token, token);
        return token;
      }
    }
    public bool IsValidUser(String user)
    {
      lock (this)
      {
        return validUsers.Any(x => x.Equals(user));
      }
    }
    public static String Xor(String input, int magic)
    {
      StringBuilder sb = new StringBuilder();
      foreach (char ch in input) sb.Append((char)(ch ^ (char)magic));
      return sb.ToString();
    }
  }
}
