using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

public partial class Enemy : Actor
{
    public int _number;
    public Player _playerOpponent;
    public Shield _shield;
    public Enemy _owner;
    public List<GoalName> _defaultGoals = new();
    public List<GoalName> _goals = new();

    
	public override void _Ready()
	{
        base._Ready();
        _board = GetNode<Board>("Board");
        _board.ClaimOwnership(this);
        _board.Disable(true);
        _defaultGoals.Add(GoalName.TopRow);
        _defaultGoals.Add(GoalName.MiddleRow);
        _defaultGoals.Add(GoalName.BottomRow);
        _defaultGoals.Add(GoalName.LeftColumn);
        _defaultGoals.Add(GoalName.MiddleColumn);
        _defaultGoals.Add(GoalName.RightColumn);
        _defaultGoals.Add(GoalName.Diagonal1To9);
        _defaultGoals.Add(GoalName.Diagonal3To7);
	}

    public virtual void PassPlayer(Player PLAYER)
    {
        _playerOpponent = PLAYER;
    }

    public void CheckGoals()
    {
        List<Shield> ownedShields = _board.GetShieldsByOwner(this);
        Goal goal = new Goal();
        for (int i = 0; i < _defaultGoals.Count; i++)
        {
            GoalName goalName = _defaultGoals[i];
            List<int> addresses = goal.GetAddresses(goalName);
            bool goalMet = addresses.All(a=>ownedShields.Select(c=>c._address).ToList().IndexOf(a)>-1);
            if (goalMet)
            {
                Victory(goalName);
                return;
            }
        }
    }

    public virtual void ClickShield(Shield CLICKED_SHIELD)
    {

    }

    public void Defeat(GoalName WINNING_PATTERN)
    {
        _board._winningPattern = WINNING_PATTERN;
        if (_owner != null)
        {
            // _owner._board.GetShieldByTenant(this).Mark(_playerOpponent);
        }
        else
        {
            _playerOpponent.RunWon();
        }
    }

    public void Victory(GoalName WINNING_PATTERN)
    {
        _board._winningPattern = WINNING_PATTERN;
        if (_owner != null)
        {
            _owner._board.GetShieldByTenant(this).Break();
        }
        else
        {
            _playerOpponent.RunLost();
        }

    }
}
