using System.Linq;
using GTANetworkAPI;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Types;
using ReallifeGamemode.Server.Util;
using ReallifeGamemode.Server.Wanted;
using ReallifeGamemode.Database.Entities;
using System;
using System.Collections.Generic;
using ReallifeGamemode.Server.Inventory.Interfaces;
using ReallifeGamemode.Database.Entities.Logs;

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

namespace ReallifeGamemode.Server.Events
{
  public class Login : Script
  {
    [RemoteEvent("CLIENT:Login_LoginRequest")]
    public void OnPlayerLogin(Player player, string password)
    {
      string username = player.Name;

      using (var dbContext = new DatabaseContext())
      {
        var user = dbContext.Users
            .Include(u => u.Group)
            .Include(u => u.BankAccount)
            .SingleOrDefault(b => b.Name == username);

        if (user == null)
        {
          player.TriggerEvent("SERVER:Login_Error", "Der Benutzer existiert nicht! Registriere dich zuerst!");
          return;
        }

        if (user.SocialClubName != player.SocialClubName && user.Password == NAPI.Util.GetHashSha256(password))
        {
          player.TriggerEvent("SERVER:Login_Error", "Dieser Benutzer gehört dir nicht!");
          //TODO ?? Log einbauen für den bösen Bub.
          player.Kick();
          return;
        }

        if (user.Password != NAPI.Util.GetHashSha256(password))
        {
          player.TriggerEvent("SERVER:Login_Error", "Passwort inkorrekt!");
          return;
        }

        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.LoginLogoutLogs.Add(logEntry);
        dbContext.SaveChanges();

        player.SetData("dbId", user.Id);
        player.Name = username;
        player.TriggerEvent("SERVER:Login_Success");
        player.TriggerEvent("CLIENT:StopSound");
        player.SetData("isLoggedIn", true);
        player.SetSharedData("isLoggedIn", JsonConvert.SerializeObject(true));
        player.SetData("spec", true);
        player.SetData("duty", false);
        player.SetData("Adminduty", false);
        player.TriggerEvent("SERVER:SET_HANDMONEY", user.Handmoney, 0);
        player.TriggerEvent("headshotoff");
        player.SetData("togdeath", true);
        Gangwar.Gangwar.loadPlayer(player);
        if (user.FactionLeader)
        {
          player.TriggerEvent("CLIENT:Turf_LoadLeaderBlip");
        }
        if (user.IsAdmin(AdminLevel.HEADADMIN))
        {
          player.SetData("editmode", false);
          player.SetData("quicksavemode", "none");
        }

        var userBankAccount = user.BankAccount;
        userBankAccount.Balance = userBankAccount.Balance;

        user.Wanteds = user.Wanteds;

        if (user.Wanteds > 0)
        {
          ChatService.HQMessage("Der Straftäter " + user.Name + " hat sich mit " + user.Wanteds + " Wanteds eingeloggt.");
        }

        if (user.Wanteds == 0)
        {
          player.TriggerEvent("enableSpawnschutz");
        }

        if (user.Group != null)
        {
          string msg = $"{player.Name} ist wieder online.";
          ChatService.BroadcastGroup(msg, user.Group);
        }

        string message = string.Empty;

        if (GlobalHelper.CustomJoinMessages.ContainsKey(player.SocialClubName))
        {
          message = "!{#FFFF00}*** " + GlobalHelper.CustomJoinMessages[player.SocialClubName] + " [ID: " + player.Handle.Value + "] (" + user.AdminLevel.GetName() + ")";
        }
        else if (user.IsAdmin(AdminLevel.MAPPING))
        {
          message = "!{#FFFF00}*** " + user.Name + " [ID: " + player.Handle.Value + "]" + " hat sich als " + user.AdminLevel.GetName() + " eingeloggt!";
        }

        string addInfoStr = " (IP: " + player.Address + ")";

        if (!string.IsNullOrEmpty(message))
        {
          ChatService.BroadcastAdmin(message, AdminLevel.MAPPING, admin =>
          {
            if (admin.HasData("togip"))
            {
              return addInfoStr;
            }
            return "";
          });
        }

        var userItems = dbContext.UserItems.Where(u => u.UserId == user.Id).ToList();
        player.SetData("items", userItems);

        user.SetBlipAndNametagColor();

        if (user.CharacterId == null)
        {
          var currentPlayerCreatorDimension = (uint)NAPI.Data.GetWorldData("playerCreatorDimension");
          currentPlayerCreatorDimension++;
          NAPI.Data.SetWorldData("playerCreatorDimension", currentPlayerCreatorDimension);
          player.Dimension = NAPI.Data.GetWorldData("playerCreatorDimension");
          player.SafeTeleport(new Vector3(402.8664, -996.4108, -99.00027));
          player.Rotation = new Vector3(0, 0, 180);
          player.TriggerEvent("toggleCreator");
        }
        else
        {
          CharacterCreator.ApplyCharacter(player);
          UpdateCharacterCloth.LoadCharacterDefaults(player);
          if (user.JailTime <= 0)
          {
            player.SafeTeleport(new Vector3(user.PositionX, user.PositionY, user.PositionZ), 0, true);
          }
          else
          {
            Jail.Check_PutBehindBars(user, JailInLocations.InCell);
          }

          player.Dimension = 0;
        }

        List<UserItem> fItem = dbContext.UserItems.Where(u => u.UserId == user.Id).ToList();
        foreach (var item in fItem)
        {
          IItem iItem = InventoryManager.GetItemById(item.ItemId);
          if (iItem is IWeaponDealItem obj)
          {
            player.SyncAnimation("carryBox");
            player.AddAttachment("ammobox", false);
            NAPI.Player.SetPlayerCurrentWeapon(player, WeaponHash.Unarmed);
            break;
          }
        }

        player.TriggerEvent("loadInventoryCEF");
        player.TriggerEvent("loadPlayerListCEF");

        player.TriggerEvent("draw", player.Name, player.Handle.Value);
        NAPI.Task.Run(() =>
        {
          if (user.Dead == true)
          {
            if (user.IsAdmin(AdminLevel.ADMIN) == true)
            {
              player.TriggerEvent("startDeathTimer", true);
            }
            else
            {
              player.TriggerEvent("startDeathTimer", false);
            }
            player.SafeSetHealth(0);
            player.SetData("isDead", true);
          }
          else
          {
            player.SetData("isDead", false);
          }
        }, delayTime: 1000);

        if (GlobalHelper.CountdownUntil > DateTime.Now)
        {
          player.TriggerEvent("countdown", (GlobalHelper.CountdownUntil - DateTime.Now).TotalSeconds, GlobalHelper.CountdownText);
        }
      }
    }
  }
}
