
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 CameraSlot:Action
  { 
    [Export]
    public VirtualCamera camera;

    [Export]
    public float priority;

    [Export]
    public SelectorFlag[] flags = [];

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


    Smoother smoother = new Smoother();

    public void Update( double delta, CameraManager manager )
    {
      if ( cameraEffectRunner != null )
      {
        if ( cameraEffectRunner.isFinished )
        {
          // this.LogInfo( "finished" );
          cameraEffectRunner = null;
          
        }
        else
        { 
          // this.LogInfo( "time:", cameraEffectRunner.timePosition, cameraEffectRunner.effect.maxDuration );
          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 );

      // this.LogInfo( "Cam Off", offset );

      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<CameraManager>();

      if ( vm == null )
      {
        return;
      }

      vm.SetActiveSlot( this );
    }


  }
}
