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

public class FollowGravity : MonoBehaviour {
    public float acceleration;
    float velocity = 0f;
    public float snapRange;
    [Header("Debug")]
    public Transform target;
    public World targetWorld;
    public World ourWorld;
    
	
	void Update () {
        velocity += acceleration * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, velocity);

        var attached = false;
        var ourTiles = new List<Tile>(ourWorld.grid.grid.Values);
        foreach (var tile in ourTiles)
            foreach (var col in Physics.OverlapSphere(tile.transform.position, snapRange))
            {
                if (attached)
                    break;
                var targetTile = col.GetComponentInParent<Tile>();
                if (targetTile == null || targetTile.world == null)
                    continue;
                if (targetTile.world == targetWorld)
                {
                    AttachToTarget();
                    this.enabled = false;
                    attached = true;
                }
            }
	}

    void AttachToTarget()
    {
        // snap ourselves into position
        transform.SetParent(target);
        var euler = transform.localRotation.eulerAngles;
        euler.y = Mathf.Round(euler.y / 60) * 60;
        transform.localRotation = Quaternion.Euler(euler);

        var targetTiles = targetWorld.tiles;
        var ourTiles = ourWorld.tiles;
        var ourOriginCoords = HexGrid.Coordinates(new Vector2(transform.localPosition.x, transform.localPosition.z));
        var ourOriginPos = HexGrid.Position(ourOriginCoords);
        transform.localPosition = new Vector3(ourOriginPos.x, 0, ourOriginPos.y);

        var targetCoords = targetWorld.tileCoords;
        var ourCoords = ourWorld.tileCoords.Select(c => c + ourOriginCoords).ToArray();

        var minPair = HexGrid.minDistancePair(targetCoords, ourCoords);
        var translation = minPair[1] - minPair[0];
        foreach (var dir in HexGrid.Direction(minPair[0], minPair[1])) // try to shift over one square to avoid overlap
        {
            translation += dir;
            ourCoords = ourCoords.Select(c => c + translation).ToArray();
            if (HexGrid.Overlap(targetCoords, ourCoords))
            {
                translation -= dir;
                continue;
            }
            break;
        }
        var transVector = HexGrid.Position(translation);
        transform.localPosition += new Vector3(transVector.x, 0, transVector.y);

        bool isPlayer = targetWorld.CompareTag("Player");

        foreach(var tile in ourTiles)
        {
            ourWorld.grid.Remove(tile);
            tile.transform.SetParent(target);
            targetWorld.grid.Add(tile);
            tile.isPlayerTile = isPlayer;
        }
        Destroy(this);
    }
}
