using Godot;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;

public partial class Board : Sprite2D
{
    public bool _active = false, _moveMade = false, _won = false;
    public List<Cell> _cells = new();
    public Enemy _owner;
    public Actor _winner = null;
    public GoalName _winningPattern;
    public override void _Ready()
    {
        _cells = GetChildren().Where(c=>c is Cell).Cast<Cell>().ToList();
        for (int i = 0; i < _cells.Count; i++)
        {
            _cells[i]._address = i;
        }
    }


    public override void _Process(double DELTA_)
	{
        
    }

    public void Activate()
    {
        Disable(false);
    }

    public Actor CheckForWinner()
    {
        // List<List<int>> playerGoalsMet = _owner._playerOpponent.CheckGoals();
        // List<List<int>> ownerGoalsMet = _owner.CheckGoals();
        // _winner = playerGoalsMet.Count>0 ? _owner._playerOpponent : ownerGoalsMet.Count>0 ? _owner : null;
        // _won = _winner != null;
        
        return _winner;
    }

    public void ClaimOwnership(Enemy OWNER)
    {
        _owner = OWNER;
        _cells.ForEach(c=>c._owner = OWNER);
        _cells.ForEach(c=>c._board = this);
    }

    public void ClearBoard(){
        foreach (Cell cell in _cells)
        {
            cell.Clear();
        }
    }

    public void Deactivate()
    {
        Disable(true);
    }

    public Cell GetCellByTenant(Enemy TENANT)
    {
        return _cells.Single(c=>c._tenant == TENANT);
    }

    public Cell GetCellByAddress(int ADDRESS)
    {
        return _cells.Single(c=>c._address == ADDRESS);
    }

    public List<Cell> GetCellsByOwner(Actor ACTOR)
    {
        return _cells.Where(c=>c._marker == ACTOR).ToList();
    }

    //THIS SHOULD BE MOVED INTO ACTION LOGIC
    // public void RotateBoard(int DEGREES, int REPEAT)
    // {
    //     for (int i = 0; i < REPEAT; i++)
    //     {
    //         Rotation += DEGREES * ((float)Math.PI / 180);
    //         RenumberCells();
    //     }
    // }

    public void RenumberCells()
    {
        GD.Print(string.Join(", ", _cells.Select(c=>c._address)));
        _cells = _cells.OrderBy(c => c.Position.Y).ThenBy(c => c.Position.X).ToList();
        GD.Print(string.Join(", ", _cells.Select(c=>c._address)));

        for (int i = 0; i < _cells.Count; i++)
        {
            _cells[i]._address = i;
        }
        
    }

    public void Start()
    {
        ClearBoard();
        // _player._isTurn = true;
    }

    public void Disable(bool DISABLED)
    {
        _active = !DISABLED;
        Visible = !DISABLED;
        SetProcess(!DISABLED);
        _cells.ForEach(c=>c.Disable(DISABLED));
    }
}
