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

namespace Baidu.VR.DepthpanoEditor
{
	[ExecuteInEditMode]
	public class DECameraPoint : MonoBehaviour
	{
		[SerializeField]
		public int Number;

		[SerializeField]
		public bool Check;

		[SerializeField]
		private Transform ground;
		
		private LineRenderer _line = null;
		private LineRenderer line
		{
			get
			{
				if (_line == null)
				{
					_line = GetComponent<LineRenderer>();
				}
				return _line;
			}
		}

		private Vector3 lastPos;
		private Vector3? groundPos;

		private void Start()
		{
			lastPos = transform.position;
			CheckGround();
		}

		public Vector3 GetPosition()
		{
			return transform.position;
		}

		public Vector3? GetGroundPosition()
		{
			return groundPos;
		}

		public void CheckGround()
		{
			RaycastHit hit;
			if (Physics.Raycast(transform.position, Vector3.down, out hit))
			{
				groundPos = hit.point;
			}
			else
			{
				groundPos = null;
			}
		}

		private void Update()
		{
			if (lastPos != transform.position)
			{
				CheckGround();
				lastPos = transform.position;
			}
		}

		private void LateUpdate()
		{
			ground.gameObject.SetActive(groundPos.HasValue);
			line.enabled = groundPos.HasValue;
			if (groundPos.HasValue)
			{
				ground.position = groundPos.Value + new Vector3(0.0f, 0.0001f, 0.0f);
				line.SetPosition(1, ground.localPosition);
			}
			transform.rotation = Quaternion.identity;
		}
	}
}