
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System;
using Godot;


namespace Rokojori
{  
  [Tool]
  [Icon("res://addons/rokojori_action_library/Icons/VirtualCamera3DSlot.svg") ]
  [GlobalClass]
  public partial class VirtualCamera3DSlot:Action
  { 
    [Export]
    public VirtualCamera3D camera;

    [Export]
    public float priority;

    CameraEffectRunner cameraEffectRunner = null;
    float _effectTimePosition = 0;
    float _smoothedPriority;
    public float smoothedPriority => _smoothedPriority;


    Smoother smoother = new Smoother();

    public void Update( double delta, VirtualCamera3DManager manager )
    {
      if ( cameraEffectRunner != null )
      {
        if ( cameraEffectRunner.isFinished )
        {
          cameraEffectRunner = null;
        }
        else
        { 
          cameraEffectRunner.Update();
        }
      }

      _smoothedPriority = smoother.SmoothWithCoefficient( _smoothedPriority, priority, 
                                                          manager.safeSmoothing, 
                                                          (float) delta, manager.smoothStepDelta );

    }

    public void SetCameraEffect( CameraEffect effect )
    {
      cameraEffectRunner = new CameraEffectRunner( effect );
    } 

    public Vector3 GetCameraPosition()
    {
      if ( camera == null )
      {
        return Vector3.Zero;
      }

      if ( cameraEffectRunner == null )
      {
        return camera.GetCameraPosition();
      }

      var offset = camera.GetGlobalOffset( cameraEffectRunner.position );

      return camera.GetCameraPosition() + offset;
    }

    public Quaternion GetCameraRotation()
    {
      if ( camera == null )
      {
        return Quaternion.Identity;
      }

      if ( cameraEffectRunner == null )
      {
        return camera.GetCameraRotation();
      }

      return camera.GetCameraRotation() * cameraEffectRunner.rotation;
    }

    public float GetCameraFOV()
    {
      if ( camera == null )
      {
        return 65;
      }

       if ( cameraEffectRunner == null )
      {
        return camera.GetCameraFOV();
      }

      return camera.GetCameraFOV() + cameraEffectRunner.fov;
    }

    protected override void _OnTrigger()
    {
      var vm = GetParent<VirtualCamera3DManager>();

      if ( vm == null )
      {
        return;
      }

      vm.SetActiveSlot( this );
    }


  }
}
