using GTANetworkAPI;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using ReallifeGamemode.Server.Entities;
using ReallifeGamemode.Server.Models;
using ReallifeGamemode.Server.Services;
using System;
using System.Collections.Generic;
using System.Linq;

/**
* @overview Life of German Reallife - Client Extension (ClientExtension.cs)
* @author hydrant
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Extensions
{
    public static class ClientExtension
    {
        /// <summary>
        /// Gibt das User-Objekt eines Client's zurück.
        /// Gibt nichts zurück, wenn der Client nicht eingeloggt ist
        /// </summary>
        /// <param name="client">Der Client, dessen User man bekommen möchte</param>
        /// <param name="context">Ein eventuell vorhandener Datenbank-Context, falls man Änderungen in der Datenbank vornehmen will</param>
        /// <returns></returns>
        public static User GetUser(this Client client, DatabaseContext context = null)
        {
            context = context ?? new DatabaseContext();
            if (!client.IsLoggedIn()) return null;
            return context
                .Users
                .Include(u => u.Faction)
                .Include(u => u.FactionRank)
                .Include(u => u.Group)
                .Include(u => u.House)
                .Where(u => u.Name == client.Name)
                .FirstOrDefault();
        }

        public static Character GetCharacter(this User user, DatabaseContext context = null)
        {
            if (context == null)
            {
                using (context = new DatabaseContext())
                {
                    return context.Characters.FirstOrDefault(u => u.UserId == user.Id);
                }
            }
            else
            {
                return context.Characters.FirstOrDefault(u => u.UserId == user.Id);
            }
        }

        /// <summary>
        /// Gibt zurück, ob ein Client eingeloggt ist
        /// </summary>
        /// <param name="player">Der Client, dessen Login-Status man bekommen möchte</param>
        /// <returns></returns>
        public static bool IsLoggedIn(this Client player)
        {
            return player.HasData("isLoggedIn") ? player.GetData("isLoggedIn") : false;
        }

        public static Vector3 GetPositionFromPlayer(Client player, float distance, int offset = 0)
        {
            var pos = player.Position;
            var a = player.Heading + offset;
            var rad = a * Math.PI / 180;
            var newpos = new Vector3(pos.X + (distance * Math.Sin(-rad)),
                pos.Y + (distance * Math.Cos(-rad)),
                pos.Z);
            return newpos;
        }

        internal static T GetData<T>(this User user, string key, T nullValue)
        {
            key += "data_";
            if (!user.Client.HasData(key)) return nullValue;
            return JsonConvert.DeserializeObject<T>(user.Client.GetData(key));
        }

        internal static T GetData<T>(this User user, string key) => user.GetData<T>(key, default);

        internal static void SetData(this User user, string key, object value)
        {
            key += "data_";
            user.Client.SetData(key, JsonConvert.SerializeObject(value));
        }

        internal static void GiveWanteds(this User user, Client cop, int amount, string reason)
        {
            if (user.Wanteds + amount > 40)
            {
                ChatService.ErrorMessage(cop, "Die Wanteds dürfen ein Limit von 40 nicht überschreiten");
                return;
            }
            using (var dbContext = new DatabaseContext())
            {
                User dbUser = dbContext.Users.Where(u => u.Id == user.Id).FirstOrDefault();
                dbUser.Wanteds += amount;
                dbContext.SaveChanges();
            }
        }
        public static FactionRank GetFactionRank(this User user)
        {
            using (var dbContext = new DatabaseContext())
            {
                FactionRank toReturn = dbContext.FactionRanks.FirstOrDefault(fR => fR.Id == user.FactionRankId);
                if (toReturn == null)
                {
                    toReturn = dbContext.FactionRanks.OrderBy(f => f.Order).FirstOrDefault(f => f.FactionId == user.FactionId);
                }

                if (toReturn == null)
                {
                    toReturn = new FactionRank
                    {
                        RankName = "Rang-Fehler"
                    };
                }

                return toReturn;
            }
        }

        public static void BanPlayer(this User user, Client admin, string reason, int mins)
        {
            using (var banUserContext = new DatabaseContext())
            {
                int unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                Ban banUser;

                if (mins == 0)
                {
                    ChatService.Broadcast("!{#FF4040}[BAN] " + user.Name + " wurde von " + admin.Name + " permanent gebannt. [" + reason + "]");
                    banUser = new Ban { UserId = user.Id, Reason = reason, BannedBy = admin.Name, Applied = unixTimestamp, UntilDateTime = unixTimestamp };

                    user.Client?.Kick();

                    mins--;
                }
                else
                {
                    ChatService.Broadcast("!{#FF4040}[BAN] " + user.Name + " wurde von " + admin.Name + " für " + mins + " Minuten gebannt. [" + reason + "]");
                    banUser = new Ban { UserId = user.Id, Reason = reason, BannedBy = admin.Name, Applied = unixTimestamp, UntilDateTime = unixTimestamp + mins * 60 };
                    user.Client?.Kick();
                }

                banUserContext.Bans.Add(banUser);
                banUserContext.SaveChanges();

                var targetUser = banUserContext.Users.Where(u => u.Name == user.Name).FirstOrDefault();
                targetUser.BanId = banUser.Id;
                banUserContext.SaveChanges();
            }
        }

        public static void UnbanPlayer(this User user)
        {
            using (var unbanUser = new DatabaseContext())
            {
                var targetUser = unbanUser.Users.Where(u => u.Id == user.Id).FirstOrDefault();
                targetUser.BanId = null;
                unbanUser.SaveChanges();
            }
        }

        public static List<UserItem> GetItems(this User user)
        {
            using (var dbContext = new DatabaseContext())
            {
                return dbContext.UserItems.Where(u => u.UserId == user.Id).ToList();
            }
        }
    }
}
