using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using Newtonsoft.Json;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Util;
using System;
using ReallifeGamemode.Database.Entities.Logs;

/**
* @overview Life of German Reallife - Event Register (Register.cs)
* @author VegaZ, balbo
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Events
{
  internal class Register : Script
  {
    [RemoteEvent("CLIENT:Login_RegisterRequest")]
    public void OnPlayerRegister(Player player, string password)
    {
      string username = player.Name;
      using (var dbContext = new DatabaseContext())
      {
        if (password.Length < 6)
        {
          player.TriggerEvent("SERVER:Login_Error", "Das Passwort muss aus mindestens 6 Zeichen bestehen.");
          return;
        }
        if (dbContext.Users.Where(u => u.SocialClubName == player.SocialClubName).Count()!= 0)
        {
          player.TriggerEvent("SERVER:Login_Error", "Es ist schon ein Konto mit dieser Socialclub-ID registriert.");
          return;
        }

        if (!dbContext.Users.Any(u => u.Name.ToLower() == username.ToLower().Trim()))
        {
          var user = new User
          {
            Name = player.Name,
            SocialClubName = player.SocialClubName,
            Password = NAPI.Util.GetHashSha256(password),
            PositionX = Main.DEFAULT_SPAWN_POSITION.X,
            PositionY = Main.DEFAULT_SPAWN_POSITION.Y,
            PositionZ = Main.DEFAULT_SPAWN_POSITION.Z,
            BankAccount = new UserBankAccount
            {
              Balance = 5000,
              Active = true
            }
          };

          var logEntry = new LoginLogoutLogEntry()
          {
            IpAddress = player.Address,
            User = user,
            PlayerId = player.Handle.Value,
            SocialClubName = player.SocialClubName,
            Username = player.Name,
            LoginLogout = true,
            Time = DateTime.Now
          };

          dbContext.Users.Add(user);
          dbContext.LoginLogoutLogs.Add(logEntry);

          dbContext.SaveChanges();

          player.SetData("dbId", user.Id);
          player.TriggerEvent("SERVER:Login_Success");
          player.TriggerEvent("CLIENT:StopSound");
          player.SetData("isLoggedIn", true);
          player.SetSharedData("isLoggedIn", JsonConvert.SerializeObject(true));
          player.SetData("isDead", false);

          var currentPlayerCreatorDimension = (uint)NAPI.Data.GetWorldData("playerCreatorDimension");
          currentPlayerCreatorDimension++;
          NAPI.Data.SetWorldData("playerCreatorDimension", currentPlayerCreatorDimension);
          player.Dimension = NAPI.Data.GetWorldData("playerCreatorDimension");
          player.TriggerEvent("toggleCreator",false);
          player.SafeTeleport(new Vector3(402.8664, -996.4108, -99.00027));
          //player.Position = new Vector3(user.PositionX, user.PositionY, user.PositionZ);

          if (GlobalHelper.CountdownUntil > DateTime.Now)
          {
            player.TriggerEvent("countdown", (GlobalHelper.CountdownUntil - DateTime.Now).TotalSeconds, GlobalHelper.CountdownText);
          }
        }
        else
        {
          player.TriggerEvent("SERVER:Login_Error", "Dieser Benutzername kann nicht registriert werden.");
        }
      }
    }
  }
}
