/*** 
@overview Life of German - Wanted (Wanted.cs)
@author kookroach
@copyright (c) 2008 - 2019 Life of German 
*/


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using GTANetworkAPI;
using ReallifeGamemode.Server.Entities;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Models;
using ReallifeGamemode.Server.Services;

namespace ReallifeGamemode.Server.Wanted
{
    public class WantedEscapeTimer
    {

        public static Dictionary<int,int> waTimer { get; set; } = new Dictionary<int, int>(); //zeit in ms

        public static void WantedTimer()
        {
            System.Timers.Timer timer = new System.Timers.Timer(2500);
            timer.Start();
            timer.Elapsed += Timer_Elapsed;
        }

        public static void ResetWantedTimeToElapse(Client client)
        {
            User user = client.GetUser();
            if (user.FactionId == 1 || user.FactionId == 3)
                return;
            
            waTimer[user.Id] = 300000;
        }


        private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (var player in NAPI.Pools.GetAllPlayers())
            {
                User user = player.GetUser();
                if(user.Wanteds > 0)
                {
                    if (!waTimer.ContainsKey(user.Id))
                        ResetWantedTimeToElapse(player);

                    bool isNearCop = false;
                    foreach (var playerCop in NAPI.Pools.GetAllPlayers())
                    {
                        User cop = playerCop.GetUser();
                        if (cop.FactionId == 1 || cop.FactionId == 3)
                        {
                            if (cop.GetData<bool>("duty") && playerCop.Position.DistanceTo2D(player.Position) <= 500)
                            {
                                //Schriftzug 'abgetaucht' zerstören :(
                                isNearCop = true;
                                break;

                            }
                            //Hier abgetaucht schriftzug einfügen :)
                        }
                    }
                                    
                    if (waTimer[user.Id] <= 0)
                    {
                        ResetWantedTimeToElapse(player);
                        using (var dbContext = new DatabaseContext())
                        {
                            player.GetUser(dbContext).Wanteds -= 1;
                            dbContext.SaveChanges();
                        }
                        
                    }
                       
                    if (!isNearCop)
                        waTimer[user.Id] -= 2500;
                }
            }
        }
    }
}
