using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.DataService.Types;

namespace ReallifeGamemode.DataService.Controllers
{
  [ApiController]
  [Authorize]
  [Route("DataService/[controller]")]
  [Produces("application/json")]
  public class UserController : ControllerBase
  {
    private readonly DatabaseContext dbContext;

    public UserController(DatabaseContext dbContext)
    {
      this.dbContext = dbContext;
    }

    [HttpGet("Data")]
    [ProducesResponseType(typeof(GetUserDataResponse), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult<GetUserDataResponse> Data()
    {
      User user = dbContext.Users
        .Include(u => u.Faction)
        .Include(u => u.FactionRank)
        .Include(u => u.BankAccount)
        .Where(u => u.Id == UserId)
        .FirstOrDefault();

      if (user == null)
      {
        return NotFound();
      }

      return new GetUserDataResponse()
      {
        Name = user.Name,
        AdminLevel = user.AdminLevel,
        RegistrationDate = user.RegistrationDate,
        BankMoney = user.BankAccount.Balance,
        HandMoney = user.Handmoney,
        FactionName = user.Faction?.Name,
        FactionRankName = user.FactionRank?.RankName,
        WantedLevel = user.Wanteds,
        CarDrivingLicense = user.DriverLicenseVehicle,
        BikeDrivingLicense = user.DriverLicenseBike,
        PlaneLicense = user.FlyingLicensePlane
      };
    }

    private int UserId => int.Parse(User.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault()?.Value ?? "0");
  }
}
