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

public class CameraController : MonoBehaviour {
  public Vector3 rotationEuler;
  public float minDistance = 12f;
  public float maxDistance = 20f;
  public float smoothness;

  public float golemZoomScale = 0.1f;
  public float golemMinPositionZoom = 5f;
  public float golemPositionLerpAmount = 0.2f;

  private PlayerController player;
  private Transform golemTransform;
  private Transform playerTransform;

  // For smoothness.
  private Vector3 velocity;

  private void Start() {
    player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
    playerTransform = player.transform;

    golemTransform = GameObject.FindGameObjectWithTag("Golem").transform;
  }

  private void Update() {
    var playerGolemDist = Vector3.Distance(playerTransform.position, golemTransform.position);

    var distanceTheta = Mathf.Clamp01((playerGolemDist - golemMinPositionZoom) * golemZoomScale);
    var cameraDistance = Mathf.Lerp(minDistance, maxDistance, distanceTheta);

    var focusPosition = Vector3.Lerp(playerTransform.position, golemTransform.position, distanceTheta * golemPositionLerpAmount);

    var cameraTargetPosition = focusPosition - transform.forward * cameraDistance;

    transform.position = Vector3.SmoothDamp(transform.position, cameraTargetPosition, ref velocity, smoothness);
    transform.rotation = Quaternion.Euler(TargetRotationEuler());
  }

  private Vector3 TargetRotationEuler() {
    return rotationEuler;
  }
}
