﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ResizePanel : MonoBehaviour, IPointerDownHandler, IDragHandler
{

    public Vector2 minSize = new Vector2(100, 100);
    public Vector2 maxSize = new Vector2(400, 400);
    public ScrollRect scrollRect;

    private RectTransform panelRectTransform;
    private RectTransform parentRectTransform;
    private Vector2 originalLocalPointerPosition;
    private Vector2 originalSizeDelta;

    private bool stayBottom = false;

    void Awake()
    {
        panelRectTransform = transform.parent as RectTransform;
        parentRectTransform = panelRectTransform.parent as RectTransform;
    }

    public void OnPointerDown(PointerEventData data)
    {
        originalSizeDelta = panelRectTransform.sizeDelta;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(panelRectTransform, data.position, data.pressEventCamera, out originalLocalPointerPosition);
        stayBottom = scrollRect.verticalNormalizedPosition == 0f;
    }

    public void OnDrag(PointerEventData data)
    {
        if (panelRectTransform == null)
            return;

        Vector2 localPointerPosition;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(panelRectTransform, data.position, data.pressEventCamera, out localPointerPosition);
        Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;

        Vector2 tmpMaxSize = maxSize;
        float tmp = parentRectTransform.rect.width - panelRectTransform.anchoredPosition.x;
        if (tmp < tmpMaxSize.x)
            tmpMaxSize.x = tmp;

        tmp = parentRectTransform.rect.height + panelRectTransform.anchoredPosition.y;
        if (tmp < tmpMaxSize.y)
            tmpMaxSize.y = tmp;

        Vector2 sizeDelta = originalSizeDelta + new Vector2(offsetToOriginal.x, -offsetToOriginal.y);
        sizeDelta = new Vector2(
            Mathf.Clamp(sizeDelta.x, minSize.x, tmpMaxSize.x),
            Mathf.Clamp(sizeDelta.y, minSize.y, tmpMaxSize.y)
        );

        panelRectTransform.sizeDelta = sizeDelta;

        if (stayBottom)
            scrollRect.verticalNormalizedPosition = 0f;
    }
}