using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using net.openstack.Providers.Rackspace;
using System.Configuration;
using net.openstack.Core.Domain;

namespace RestApiTest
{
    class CredentialsManager
    {
        private static volatile CredentialsManager Instance;
        private static readonly object padlock = new Object();

        private UserAccess _AdminUser;
        private UserAccess _RegisteredUser;
        private UserAccess _NonRegisteredUser;

        public static UserAccess AdminUser { get { return GetInstance()._AdminUser; } }
        public static UserAccess RegisteredUser { get { return GetInstance()._RegisteredUser; } }
        public static UserAccess NonRegisteredUser { get { return GetInstance()._NonRegisteredUser; } }

        public string KeystoneUri;

        private CredentialsManager() 
        {
            this.KeystoneUri = ConfigurationManager.AppSettings["KeystoneUri"];
            var identityProvider = new CloudIdentityProvider(new Uri(this.KeystoneUri));

            var adminUserIdentity = new ExtendedCloudIdentity() 
            {
                Username = ConfigurationManager.AppSettings["AdminUser.Username"],
                TenantName = ConfigurationManager.AppSettings["AdminUser.TenantName"],
                Password = ConfigurationManager.AppSettings["AdminUser.Password"]
            };

            var registeredUserIdentity = new ExtendedCloudIdentity()
            {
                Username = ConfigurationManager.AppSettings["RegisteredUser.Username"],
                TenantName = ConfigurationManager.AppSettings["RegisteredUser.TenantName"],
                Password = ConfigurationManager.AppSettings["RegisteredUser.Password"]
            };

            var nonRegisteredUserIdentity = new ExtendedCloudIdentity()
            {
                Username = ConfigurationManager.AppSettings["NonRegisteredUser.Username"],
                TenantName = ConfigurationManager.AppSettings["NonRegisteredUser.TenantName"],
                Password = ConfigurationManager.AppSettings["NonRegisteredUser.Password"]
            };

            _AdminUser = identityProvider.GetUserAccess(adminUserIdentity);
            _RegisteredUser = identityProvider.GetUserAccess(registeredUserIdentity);
            _NonRegisteredUser = identityProvider.GetUserAccess(nonRegisteredUserIdentity);
        }

        public static CredentialsManager GetInstance()
        {
            lock (padlock)
            {
                if (Instance == null)
                {
                    Instance = new CredentialsManager();
                }
            }

            return Instance;
        }
    }

    class Credentials
    {
        public string UserName;
        public string TenantName;
        public string Password;

        public string UserId;
        public UserAccess UserAccess;
    }
}
