using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

[Serializable]
public class Game
{
    public delegate void GameOverHandler(Player winner);

    public event GameOverHandler GameOver;


    public GameData Data { get; private set; }
    public List<Player> Players { get; private set; }
    public float StartTime { get; private set; }

    public Game(GameData data)
    {
        Data = data;
        Players = new List<Player>();
    }

    public Player AddPlayer(PlayerData data, int playerId)
    {
        if (Players.Count >= Data.MaxPlayers)
        {
            Debug.LogWarning("Game is full");
            return null;
        }
        var player = new Player(data, playerId != -1 ? playerId : Players.Count);
        player.PlayerHit += PlayerHit;
        player.PlayerKilled += PlayerKilled;
        Players.Add(player);
        return player;
    }

    private void PlayerKilled(Player player, GameEntity killer)
    {
        Debug.LogFormat("Player {0} has been killed by {1}", player.PlayerId, killer.Name);
        RemovePlayer(player);
        player.PlayerKilled -= PlayerKilled;
        player.PlayerHit -= PlayerHit;
//        player.PlayerFire -= PlayerFire;

        if (Players.Count <= 1)
        {
            if (GameOver != null)
            {
                GameOver(Players.FirstOrDefault());
            }
        }
    }

    private void PlayerHit(Player player, int amount, GameEntity source)
    {
        Debug.LogFormat("Player {0} has been hit for {1} damage by {3}. Remaining: {2}", player.PlayerId, amount, player.HitPoints, source.Name);

    }

    public bool RemovePlayer(Player player)
    {
        if (Players.Contains(player))
        {
            return Players.Remove(player);
        }

        return false;
    }

    public void Start()
    {
        StartTime = Time.timeSinceLevelLoad;
    }
}
