using System;
using System.Collections;
using System.Collections.Generic;
//using System.Linq;

//using UnityEditor;
using UnityEngine;
//using UnityEngine.UI;
//using Uhity.Entities;

using URD = UnityEngine.Random;

public class DragItem : MonoBehaviour {
	
	public Camera cam;
	
	public LayerMask pickMask = 1<<8, dragMask = 1;
	
	public float dragForce = 10f;
	public float dragUpModify = 2f;
	public float radios = 0.5f;
	
	public float maxSpeed = 5f;
	
	public Rigidbody draged;
	
	private void CheckDrag() {
		RaycastHit hit;
		var ray = cam.ScreenPointToRay(Input.mousePosition);
		
		if(Physics.SphereCast(ray, radios, out hit, Mathf.Infinity, pickMask)) {
			draged = hit.transform.GetComponent<Rigidbody>();
		}
		
		
	}
	
	private void ReleaseDrag() {
		draged = null;
	}
	
	private void DragObject() {
		RaycastHit hit;
		var ray = cam.ScreenPointToRay(Input.mousePosition);
		
		if(Physics.SphereCast(ray, radios, out hit, Mathf.Infinity, dragMask)) {
			var disp = hit.point + Vector3.up*0.5f	- draged.worldCenterOfMass;
			
			if(disp.y > 0)
				disp.y *= dragUpModify;
			
			draged.AddForce(disp * dragForce, ForceMode.Acceleration);
		}
		
	}
	
	
	// Update is called once per frame
	void Update() {
		
		if(Input.GetMouseButtonDown(0))
			CheckDrag();
		if(Input.GetMouseButtonUp(0))
			ReleaseDrag();
		
		
		if(draged != null)
			DragObject();
	}
}
