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

public class DeployableCam : MonoBehaviour
{
    public Transform CopyRotation;
    public LayerMask MirrorLayer;

    public bool NextStick { get; set; }

    private RenderTexture _renderTexture;

    private AudioSource source;

    private void Awake()
    {
        NextStick = false;
        _renderTexture = GetComponentInChildren<Camera>().targetTexture;
        source = this.GetComponent<AudioSource>();
    }

    private void Update()
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, CopyRotation.rotation, 0.1f);
    }

    private void HandleStick(Collision collision)
    {
        bool b = ((0x1 << collision.gameObject.layer) & MirrorLayer.value) == 0;
        if (NextStick && b)
        {
            NextStick = false;

            Ray r = new Ray(collision.contacts[0].point + collision.contacts[0].normal, collision.contacts[0].normal);
            RaycastHit info;

            float up = 0.5f;
            Vector3 upPoint = collision.contacts[0].point + up * collision.contacts[0].normal;
            if (Physics.Raycast(r, out info, up))
            {
                upPoint = info.point - info.normal * 0.4f;
            }
            StartCoroutine("MoveIntoPlace", upPoint);
            GetComponent<Rigidbody>().velocity = Vector3.zero;
            GetComponent<Rigidbody>().isKinematic = true;
        }
    }

    private IEnumerator MoveIntoPlace(Vector3 target)
    {
        while ((target - transform.position).magnitude < 0.001f)
        {
            transform.position = Vector3.Slerp(transform.position, target, 0.5f);
            yield return new WaitForFixedUpdate();
        }
    }

    private void OnCollisionStay(Collision collision)
    {
        HandleStick(collision);
    }

    private void OnCollisionEnter(Collision collision)
    {
        HandleStick(collision);
        source.Play();
    }
}