namespace Marro.PacManUdon
{
    using System;
    using UnityEngine;

    public abstract class GridMover : SyncedObject
    {
        protected Vector2 direction;

        public virtual Vector2 GetPosition()
        {
            return (Vector2)transform.localPosition;
        }

        public virtual void SetPosition(Vector2 position)
        {
            transform.localPosition = new Vector3(position.x, position.y, transform.localPosition.z);
        }

        public virtual Vector2 GetDirection()
        {
            return direction;
        }

        public void SetDirection(Vector2 direction)
        {
            this.direction = direction;
            UpdateAnimator();
        }

        protected abstract void UpdateAnimator();

        public override void CollectSyncedData(byte[] data, ref int index, NetworkEventType eventType)
        {
            if (eventType != NetworkEventType.PacManTurn)
            {
                return;
            }

            data.Append(GetPosition(), ref index);
            data.Append(GetDirection(), ref index);
        }

        public override bool WriteSyncedData(byte[] data, ref int index, NetworkEventType eventType)
        {
            if (eventType != NetworkEventType.PacManTurn)
            {
                return true;
            }

            SetPosition(data.ReadVector2(ref index));
            SetDirection(data.ReadVector2(ref index));

            return true;
        }
    }
}