using System;
using Actions;
using UnityEngine;

public class CameraManager : MonoBehaviour {
    [SerializeField] private GameObject actionCameraGameObject;
    private void Awake() => HideActionCamera();
    private const float shoulderOffsetAmount = .5f;
    private readonly Vector3 cameraCharacterHeight = Vector3.up * 1.7f;

    private void Start() {
        BaseAction.OnAnyActionStarted += BaseAction_OnAnyActionStarted;
        BaseAction.OnAnyActionEnded += BaseAction_OnAnyActionEnded;
    }

    private void BaseAction_OnAnyActionStarted(object sender, EventArgs e) {
        switch (sender) {
            case ShootAction shootAction:
                Unit shooterUnit = shootAction.Unit;
                Unit targetUnit = shootAction.TargetUnit;
                
                Vector3 shootDir = (targetUnit.GetWorldPosition() - shooterUnit.GetWorldPosition()).normalized;
                Vector3 shoulderOffset = Quaternion.Euler(0, 90, 0) * shootDir * shoulderOffsetAmount;
                Vector3 actionCameraPosition = shooterUnit.GetWorldPosition() + cameraCharacterHeight + shoulderOffset + (shootDir * -1);
                
                actionCameraGameObject.transform.position = actionCameraPosition;
                actionCameraGameObject.transform.LookAt(targetUnit.GetWorldPosition() + cameraCharacterHeight);
                
                ShowActionCamera();
                break;
        }
    }
    
    private void BaseAction_OnAnyActionEnded(object sender, EventArgs e) {
        switch (sender) {
            case ShootAction:
                HideActionCamera();
                break;
        }
    }

    private void ShowActionCamera() => actionCameraGameObject.SetActive(true);
    private void HideActionCamera() => actionCameraGameObject.SetActive(false);
}
