using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using CoviDok.Api;
using CoviDok.Data.SessionProviders;
using NCuid;

namespace CoviDok.BLL.Sessions
{
    class SessionHandler
    {
        private readonly ISessionProvider SessionStore;

        public SessionHandler()
        {
            SessionStore = new RedisProvider();
        }

        public async Task<Session> GetSession(string SessionId)
        {
            if (string.IsNullOrEmpty(SessionId)) throw new UnauthorizedAccessException();
            string Candidate = SessionStore.Get(SessionId);
            if (Candidate == null) throw new UnauthorizedAccessException();
            Session session = null;
            await Task.Run(() => {
                session = JsonSerializer.Deserialize<Session>(Candidate);
                session.LastAccess = DateTime.Now;
                SessionStore.Set(SessionId, JsonSerializer.Serialize(session));
            });            
            return session;
        }

        public async Task<string> CreateSession(Role UserType, int UserId)
        {
            string Id = null;
            await Task.Run(() => {
                Session session = new Session
                {
                    Id = UserId,
                    Type = UserType,
                    LastAccess = DateTime.Now
                };
                Id = Cuid.Generate();
                SessionStore.Set(Id, JsonSerializer.Serialize(session));
            });            
            return Id;
        }

        public void DeleteSession(string SessionId)
        {
            SessionStore.Del(SessionId);
        }
    }
}