using UnityEngine;

public sealed class OutpostAssemblyUnit : MonoBehaviour
{
    [SerializeField]
    private Army army = null;
    [SerializeField]
    private float speed = 1f;
    [SerializeField]
    private UnitFactory unitFactory = null;

    public Faction Faction { get; private set; } = null;
    private ControlPoint targetPoint = null;

    public void Init(Faction faction, ControlPoint point)
    {
        Faction = faction;
        targetPoint = point;
        if (point == null)
            Destroy(gameObject);
    }

    private void Update()
    {
        ProcessMove();
    }

    private void ProcessMove()
    {
        var direction = targetPoint.transform.position - transform.position;
        var moveDistance = speed * Time.deltaTime;
        if (direction.sqrMagnitude < moveDistance * moveDistance)
        {
            transform.position = targetPoint.transform.position;
            if (targetPoint.Base == null)
            {
                unitFactory.CreateOutpost(Faction, targetPoint);
            }
            else
            {
                Destroy(gameObject);
            }
        }
        else
        {
            transform.position += direction.normalized * moveDistance;
            var angle = Utils.GetAngle(new Vector2(direction.x, direction.z));
            army.SetAngle(angle);
        }
    }
}
