using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent(typeof(BoxCollider2D))]
public class PanController : MonoBehaviour, IDragHandler, IBeginDragHandler
{
    [SerializeField] private Transform target;
    [SerializeField] private Collider2D targetBorder;
    [SerializeField, ReadOnly] private string deltaString;
    private Vector3 firstPos;
    private Vector3 prevPos;
    private Vector3 offset;
    
    private Vector2 velocity;
    public Vector2 Velocity => velocity;

    void Awake()
    {
        firstPos = target.position;
        prevPos = firstPos;
    }

    private void OnDisable()
    {
        velocity = Vector2.zero;
    }

    // Update is called once per frame
    void Update()
    {
        // OnDragが更新されていないフレームでは0にする
        if (target.position == prevPos)
        {
            velocity = Vector2.zero;
        }
        prevPos = target.position;
#if UNITY_EDITOR
        deltaString = $"delta: {velocity.normalized} {velocity.magnitude:F3}";
#endif
    }


    public void OnDrag(PointerEventData eventData)
    {
        var targetPos = target.position;
        var currentPoint = Camera.main.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, targetPos.z));
        var pos = currentPoint + offset;
        // 移動範囲を制限
        pos = targetBorder.bounds.ClosestPoint(pos);
        velocity = (pos - targetPos) / Time.deltaTime;
        target.position = pos;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        // ドラッグ開始時のobjectのpositionからのズレを記憶
        var targetPos = target.position;
        offset = targetPos - Camera.main.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y,
            targetPos.z));
    }

    public void ResetTargetPosition()
    {
        target.position = firstPos;
    }
}
