using NetworkResurrector.Server.Domain.Models;
using System.Collections.Generic;
using System.Linq;

namespace NetworkResurrector.Server.Application.Stores
{
    public class SecurityStore : ISecurityStore
    {
        private List<SecurityToken> Tokens { get; }

        public SecurityStore()
        {
            Tokens = new List<SecurityToken>();
        }

        public void SetToken(string token, int userId)
        {
            var registered = Tokens.FirstOrDefault(z => z.UserId == userId);
            if (registered == null)
                Tokens.Add(new SecurityToken() { UserId = userId, Token = token });
            else
                registered.Token = token;
        }

        public TokenValidation ValidateToken(string token)
        {
            var lastIndexOfSeparator = token.LastIndexOf('-') + 1;
            var userIdString = token.Substring(lastIndexOfSeparator, token.Length - lastIndexOfSeparator);

            if (!int.TryParse(userIdString, out int userId))
                return InvalidToken;

            var valid = Tokens.FirstOrDefault(z => z.UserId == userId && z.Token == token);
            if (valid != null)
                return new TokenValidation() { Success = true, UserId = userId };

            return InvalidToken;
        }

        private TokenValidation InvalidToken => new TokenValidation() { Success = false };
    }
}