using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Server.Models;

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

namespace ReallifeGamemode.Server.Events
{
    class Register : Script
    {
        [RemoteEvent("CLIENT:Login_RegisterRequest")]
        public void OnPlayerRegister(Client player, string username, string password, string passwordRepeat)
        {
            using (var dbContext = new DatabaseContext())
            {
                if (!dbContext.Users.Any(u => u.Name.ToLower() == username.ToLower().Trim()))
                {
                    var user = new Entities.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
                    };

                    dbContext.Users.Add(user);
                    dbContext.SaveChanges();
                    var userBankAccount = new Entities.UserBankAccount
                    {
                        UserId = user.Id,
                        Balance = 5000,
                        Active = true
                    };

                    dbContext.UserBankAccounts.Add(userBankAccount);
                    dbContext.SaveChanges();

                    player.TriggerEvent("SERVER:Login_Success");
                    player.SetData("isLoggedIn", 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");
                    player.Position = new Vector3(402.8664, -996.4108, -99.00027);
                    //player.Position = new Vector3(user.PositionX, user.PositionY, user.PositionZ);
                    
                }
                else if (dbContext.Users.Where(u => u.SocialClubName == player.SocialClubName).Count() >= 3)
                {
                    player.TriggerEvent("SERVER:Login_Error", "Es sind schon 3 Konten mit dieser Socialclub-ID registriert.");
                }
                else
                {
                    player.TriggerEvent("SERVER:Login_Error", "Dieser Benutzername kann nicht registriert werden.");
                }
            }
        }
    }
}
