using System;
using Wall.Configuration.Startup;
using Wall.MultiTenancy;

namespace Wall.Runtime.Session
{
    public abstract class WallSessionBase : IWallSession
    {
        public const string SessionOverrideContextKey = "Wall.Runtime.Session.Override";

        public IMultiTenancyConfig MultiTenancy { get; }

        public abstract long? UserId { get; }

        public abstract int? TenantId { get; }

        public abstract long? ImpersonatorUserId { get; }

        public abstract int? ImpersonatorTenantId { get; }

        public virtual MultiTenancySides MultiTenancySide => MultiTenancy.IsEnabled && !TenantId.HasValue
            ? MultiTenancySides.Host
            : MultiTenancySides.Tenant;

        protected SessionOverride OverridedValue => SessionOverrideScopeProvider.GetValue(SessionOverrideContextKey);

        protected IAmbientScopeProvider<SessionOverride> SessionOverrideScopeProvider { get; }

        protected WallSessionBase(IMultiTenancyConfig multiTenancy, IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider)
        {
            MultiTenancy = Check.NotNull(multiTenancy, nameof(multiTenancy));
            SessionOverrideScopeProvider = Check.NotNull(sessionOverrideScopeProvider, nameof(sessionOverrideScopeProvider));
        }

        public IDisposable Use(int? tenantId, long? userId)
        {
            return SessionOverrideScopeProvider.BeginScope(SessionOverrideContextKey, new SessionOverride(tenantId, userId));
        }
    }
}