using System;
using System.Collections.Generic;
using System.Linq;
using Interfaces;
using Nancy;
using Nancy.Authentication.Forms;
using Nancy.Security;

namespace RaceLapTimer
{
    public class UserDatabase : IUserMapper
    {
        private static List<Tuple<string, string, Guid>> _users = new List<Tuple<string, string, Guid>>();
        private IUserStorage _storage;

        public UserDatabase(IUserStorage storage)
        {
            _storage = storage;
            _users.Add(new Tuple<string, string, Guid>("admin", "password", new Guid("55E1E49E-B7E8-4EEA-8459-7A906AC4D4C0")));
            _users.Add(new Tuple<string, string, Guid>("user", "password", new Guid("56E1E49E-B7E8-4EEA-8459-7A906AC4D4C0")));
        }
        
        /// <summary>
        /// Get the user from the database
        /// </summary>
        /// <param name="identifier">The Guid identifier for the user</param>
        /// <param name="context">NancyContext (injected)</param>
        /// <returns></returns>
        public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
        {
            var userRecord = _users.FirstOrDefault(u => u.Item3 == identifier);
            return userRecord == null
                       ? null
                       : new NancyUser(userRecord.Item1);
        }

        /// <summary>
        /// Validate that the user/password combo is a valid user.
        /// </summary>
        /// <param name="username">the username of the user attempting to authenticate</param>
        /// <param name="password">the password of the user to authenticate.</param>
        /// <returns>Returns Guid if valid user, null if not.</returns>
        public static Guid? ValidateUser(string username, string password)
        {
            var pwHash = string.Empty;
            if (!string.IsNullOrEmpty(password))
            {
                pwHash = Helpers.Encryption.Hash.HashString(password);
            }

            var userRecord = _users.FirstOrDefault(u => u.Item1 == username && u.Item2 == password);

            return userRecord?.Item3;
        }
    }

    public class UserStorage : IUserStorage
    {
        public UserStorage()
        {
        }

        public User GetUser(int id)
        {
            throw new NotImplementedException();
        }

        public User GetUser(string guid)
        {
            throw new NotImplementedException();
        }

        public bool DeleteUser(int id)
        {
            throw new NotImplementedException();
        }

        public bool DeleteUser(string guid)
        {
            throw new NotImplementedException();
        }

        public bool UpdateUser(User user)
        {
            throw new NotImplementedException();
        }

        public bool CreateUser(User user)
        {
            throw new NotImplementedException();
        }
    }
}
