﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Arugula.Prototypical
{
    [RequireComponent(typeof(Camera))]
    public class RigidbodyDragMouse : RigidbodyDrag
    {
        [Header("Mouse")]
        public float maxRayDistance = 1000;
        public LayerMask objectMask;
        public Vector3 offsetAxis = Vector3.down;
        public float offset = 0;

        Plane plane;
        Camera cam;
        private void Start()
        {
            cam = GetComponent<Camera>();
            InputSystem.onAfterUpdate += PerformUpdate;
        }

        private void OnDestroy()
        {
            InputSystem.onAfterUpdate -= PerformUpdate;
        }

        Ray dray;
        private void OnDrawGizmos()
        {
            Gizmos.DrawRay(dray);
        }
        private void PerformUpdate()
        {
            Ray ray = cam.ScreenPointToRay(Mouse.current.position.ReadValue());
            if (Mouse.current.leftButton.wasPressedThisFrame)
            {
                RaycastHit hit = new RaycastHit();
                if (Physics.Raycast(ray, out hit, maxRayDistance, objectMask, QueryTriggerInteraction.Ignore))
                {
                    if (hit.rigidbody)
                    {
                        StartDragging(hit.rigidbody, hit.point);
                        plane = new Plane(offsetAxis * -1, hit.point);
                    }
                }
            }

            if (Mouse.current.leftButton.isPressed)
            {

                float dist = 0;
                if (plane.Raycast(ray, out dist))
                {
                    Vector3 pos = ray.GetPoint(dist);
                    Drag(pos + (offsetAxis * offset));
                }

            }
            else if (Mouse.current.leftButton.wasReleasedThisFrame || !Mouse.current.leftButton.isPressed)
            {
                StopDragging();
            }
        }
    }

}
