using MarketData;
using MarketData.DataAccess;
using MarketData.Extensions;
using MarketData.MarketDataModel.User;
using System.Text;

namespace MarketDataServer.Authorization
{
  public class Authorizations
  {
    private Dictionary<String, String> authorizationDictionary = null;
    private static Authorizations authorizations = null;
    private bool isEnabled=true;

    private Authorizations()
    {
      authorizationDictionary=new Dictionary<String,String>();
    }

    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 username,String password)
    {
      lock (this)
      {
        if(!UserDA.UserExists(username))return false;
        MDTrace.WriteLine(MarketData.LogLevel.DEBUG,String.Format("[{0:G}][User {1} exists.]",DateTime.Now ,username));
        User user = UserDA.GetUser(username);
        if(null == user)
        {
          MDTrace.WriteLine(MarketData.LogLevel.DEBUG,String.Format("[{0:G}][User {1} validation failed.]",DateTime.Now ,username));
          return false;
        }
        MDTrace.WriteLine(MarketData.LogLevel.DEBUG,String.Format("[{0:G}][User {1} is validated.]",DateTime.Now ,username));
        return user.Verify(password);
      }
    }

    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();
    }
  }
}
