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

namespace ReallifeGamemode.Server.Events
{
    class Faction : Script
    {
        [RemoteEvent("OnFactionRanksEdit")]
        public void OnFactionRanksEdit(Client player, string jsonData)
        {
            FactionRankHelper helper = JsonConvert.DeserializeObject<FactionRankHelper>(jsonData);
            using (var context = new DatabaseContext())
            {
                Entities.Faction f = context.Factions.FirstOrDefault(x => x.Id == helper.FactionId);
                if (f == null)
                {
                    ChatService.ErrorMessage(player, "Bei der Bearbeitung der Ränge ist ein Fehler aufgetreten: Die Fraktion existiert nicht");
                    return;
                }

                List<Rank> ranks = helper.Ranks;
                int length = ranks.Count;

                List<FactionRank> factionRanks = context.FactionRanks.ToList().FindAll(fR => fR.FactionId == f.Id);

                List<int> found = new List<int>();

                for (int i = 0; i < ranks.Count; i++)
                {
                    Rank newRank = ranks[i];
                    if (newRank.Id == 0)
                    {
                        context.FactionRanks.Add(new FactionRank
                        {
                            RankName = newRank.Name,
                            FactionId = f.Id,
                            Order = length - i
                        });
                    }
                    else
                    {
                        FactionRank factionRank = factionRanks.Find(r => r.Id == newRank.Id);
                        factionRank.RankName = newRank.Name;
                        factionRank.Order = length - i;
                        found.Add(factionRank.Id);
                    }
                }

                for (int i = 0; i < factionRanks.Count; i++)
                {
                    if (!found.Contains(factionRanks[i].Id))
                    {
                        context.FactionRanks.Remove(factionRanks[i]);
                    }
                }

                ChatService.SendMessage(player, "~g~Die Ränge wurden erfolgreich gespeichert.");
                context.SaveChanges();
            }
        }
    }
}
