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

namespace Rokojori
{
  [Tool]
  [GlobalClass]
  public partial class LODNode:MeshInstance3D
  {
    [Export]
    public LODArrangement arrangement;

    LODLevel _currentLevel;

    public override void _Process( double delta ) 
    {
      if ( arrangement == null )
      {
        return;
      }

      _hasCameraDirection = false;
      _hasDistance = false;
      _hasPitch = false;
      _hasYaw = false;

      var level = arrangement.GetLevel( this );

      if ( level == _currentLevel )
      {
        return;
      }

      Mesh = level.mesh;
      MaterialOverride = level.material;
    }


     public Camera3D camera 
    {
      get 
      {
        var _camera = GetViewport().GetCamera3D();

#if TOOLS 

        if ( Engine.IsEditorHint() )
        {
          _camera = EditorInterface.Singleton.GetEditorViewport3D().GetCamera3D();
        }
      
#endif

        return _camera;

      }

    }

    bool _hasCameraDirection = false;
    Vector3 _cameraDirection;

    public Vector3 cameraDirection
    {
      get
      {
        if ( _hasCameraDirection )
        {
          return _cameraDirection;
        }

        _cameraDirection = ( GlobalPosition - camera.GlobalPosition );

        return _cameraDirection;
      }
    }

    bool _hasDistance = false;
    float _distance = 0;
  
    public float distance 
    {
      get 
      {
        if ( _hasDistance )
        {
          return _distance;
        }

        _distance = cameraDirection.Length();

        return _distance;
      }
    }

    bool _hasPitch = false;
    float _pitch = 0;

    public float pitch 
    {
      get 
      {
        if ( _hasPitch )
        {
          return _pitch;
        }

        _pitch = Math3D.GlobalPitch( cameraDirection );

        return _pitch;
      }
    }

    bool _hasYaw = false;
    float _yaw = 0;

    public float yaw 
    {
      get 
      {
        if ( _hasYaw )
        {
          return _yaw;
        }

        _yaw = Math3D.GlobalYaw( cameraDirection );

        return _yaw;
      }
    }

    

  
  }
}