using System;
using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Server.Models;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Util;
using ReallifeGamemode.Server.Wanted;

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

namespace ReallifeGamemode.Server.Events
{
    class Connect : Script
    {
        [ServerEvent(Event.PlayerConnected)]
        public void OnPlayerConnected(Client player)
        {
            player.SetData("isLoggedIn", false);
            player.Position = new Vector3(-1883.736, -781.4911, -10);
            player.FreezePosition = true;

            using (var dbContext = new DatabaseContext())
            {
                if (!dbContext.WhitelistEntries.Any(w => w.SocialClubName.ToLower() == player.SocialClubName.ToLower()))
                {
                    string msg2 = "~m~*** " + player.Name + "[" + player.SocialClubName + "] (" + player.Address + ") hat versucht, sich einzuloggen, steht aber nicht auf der Whitelist.";
                    ChatService.BroadcastAdmin(msg2, AdminLevel.ADMIN);

                    NAPI.Util.ConsoleOutput(player.Name + " tried to join without whitelist entry");

                    ChatService.SendMessage(player, "~m~Du stehst nicht auf der Whitelist");

                    player.Kick();
                    return;
                }
            }

            if (IsPlayerBanned(player)) return;
            player.TriggerEvent("SERVER:Login_ShowBrowser");
            string msg = "~m~*** " + player.Name + " [" + player.SocialClubName + "] [ID:" + player.Handle.Value + "] (" + player.Address + ")";
            ChatService.BroadcastAdmin(msg, AdminLevel.ADMIN);
            
        }

        private bool IsPlayerBanned(Client player)
        {
            using (var dbContext = new DatabaseContext())
            {
                var user = dbContext.Users.SingleOrDefault(b => b.Name == player.Name);
                if (user == null)
                {
                    return false;
                }
                if (user.BanId != null)
                {
                    var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    var bannedUser = dbContext.Bans.SingleOrDefault(u => u.Id == user.BanId);
                    if (bannedUser.Applied == bannedUser.UntilDateTime)
                    {
                        ChatService.SendMessage(player, "!{#FF4040}Du wurdest permanent gebannt! [" + bannedUser.Reason + "]");
                        player.Kick();
                        return true;
                    }
                    else
                    {
                        var timeStamp = bannedUser.UntilDateTime;
                        int unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                        if (timeStamp > unixTimestamp)
                        {
                            ChatService.SendMessage(player, "Du bist noch bis zum !{#FF4040}" + dt.AddSeconds(timeStamp).ToLocalTime() + " Uhr ~s~gebannt. [" + bannedUser.Reason + "]");
                            player.Kick();
                            return true;
                        }
                        else
                        {
                            user.BanId = null;
                            dbContext.SaveChanges();
                            return false;
                        }
                    }
                }
                return false;
            }
        }
    }
}