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

public class UnitManager : MonoBehaviour
{
    public List<Unit> leftSideUnits = new List<Unit>();
    public List<Unit> rightSideUnits = new List<Unit>();

    // Start is called before the first frame update
    void Start()
    {
        var units = FindObjectsOfType<Unit>();
        foreach (var unit in units)
        {
            if (unit.side == Side.left)
            {
                leftSideUnits.Add(unit);
            }
            else
            {
                rightSideUnits.Add(unit);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void handleDiedUnit(Unit unit)
    {
        if (unit.side == Side.left)
        {
            leftSideUnits.Remove(unit);
        }
        else if (unit.side == Side.right)
        {
            leftSideUnits.Remove(unit);
        }
    }

    bool test = true;
    public void SideAction()
    {
        if (test)
        {
            SortActionOrder(Side.right);
            foreach (var unit in rightSideUnits)
            {
                if (unit.isUnitAlive())
                {
                    unit.MoveAction();
                }

                if (unit.isUnitAlive())
                {
                    unit.AttackAction();
                }
            }
        }
        else
        {
            SortActionOrder(Side.left);
            foreach (var unit in leftSideUnits)
            {
                if (unit.isUnitAlive())
                {
                    unit.MoveAction();
                }

                if (unit.isUnitAlive())
                {
                    unit.AttackAction();
                }
            }
        }

        test = !test;
    }

    private void SortActionOrder(Side side)
    {
        switch (side)
        {
            case Side.left:
                leftSideUnits = leftSideUnits.OrderByDescending(x => x.standingCell.xPos).ThenByDescending(y => y.standingCell.yPos).ToList<Unit>();
                break;
            case Side.right:
                rightSideUnits = rightSideUnits.OrderBy(x => x.standingCell.xPos).ThenBy(y => y.standingCell.yPos).ToList<Unit>();
                break;
            default:
                break;
        }
    }

}