using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using ReallifeGamemode.Database;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Types;

namespace ReallifeGamemode.DataService.Logic
{
  public class JwtTokenGenerator : LogicBase
  {
    private readonly ILogger<JwtTokenGenerator> logger;
    private readonly ServerConfig config;

    public JwtTokenGenerator(IOptions<ServerConfig> config, DatabaseContext dbContext, ILogger<JwtTokenGenerator> logger) : base(dbContext)
    {
      this.config = config.Value;
      this.logger = logger;
    }

    public string GenerateUserToken(User user)
    {
      if (user == null)
      {
        return null;
      }

      var tokenHandler = new JwtSecurityTokenHandler();

      var key = Encoding.ASCII.GetBytes(config.TokenSecret);

      var tokenDescriptor = new SecurityTokenDescriptor
      {
        Subject = new ClaimsIdentity(new[]
          {
            new Claim(ClaimTypes.Name, user.Id.ToString()),
            new Claim(ClaimTypes.Role, user.AdminLevel.ToString())
          }),
        Expires = DateTime.UtcNow.AddDays(1),
        IssuedAt = DateTime.UtcNow,
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
      };

      var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

      return token;
    }

    public string GetDebugToken(byte[] key)
    {
      var tokenHandler = new JwtSecurityTokenHandler();

      var tokenDescriptor = new SecurityTokenDescriptor
      {
        Subject = new ClaimsIdentity(new[]
          {
            new Claim(ClaimTypes.Name, 1.ToString()),
            new Claim(ClaimTypes.Role, (AdminLevel.PROJEKTLEITUNG).ToString())
          }),
        Expires = DateTime.UtcNow.AddDays(1),
        IssuedAt = DateTime.UtcNow,
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
      };

      var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

      return token;
    }
  }
}
