// Copyright (c) 2017 Intel Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SRC_EXECUTOR_H_
#define SRC_EXECUTOR_H_

#include <napi.h>
#include <rcl/guard_condition.h>
#include <rcl/subscription.h>
#include <rcl/wait.h>
#include <uv.h>

#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <exception>
#include <mutex>
#include <string>
#include <vector>

#include "rcl_handle.h"

namespace rclnodejs {

class HandleManager;
struct RclResult;

class Executor {
 public:
  class Delegate {
   public:
    virtual void Execute(const std::vector<rclnodejs::RclHandle*>& handles) = 0;
    virtual void CatchException(std::exception_ptr e_ptr) = 0;
  };

  Executor(Napi::Env env, HandleManager* handle_manager, Delegate* delegate);
  ~Executor();

  void Start(rcl_context_t* context, int32_t time_out);
  void Stop();
  void SpinOnce(rcl_context_t* context, int32_t time_out);
  void SynchronizeHandles(const Napi::Object& node);
  rcl_ret_t SetSubscriptionContentFilter(
      const rcl_subscription_t* subscription,
      const rcl_subscription_content_filter_options_t* options);
  int32_t time_out() { return time_out_; }
  bool IsStopped() const;

  static void DoWork(uv_async_t* handle);
  static void Run(void* arg);

 private:
  enum class ExecutorState {
    Stopped,
    Starting,
    Running,
    ThreadJoinPending,
    ReleasingResources,
  };

  enum class WaitMode {
    Synchronous,
    Background,
  };

  bool IsRunning() const { return state_.load() == ExecutorState::Running; }

  // Called only when no worker remains to be joined.
  std::string ReleaseResources();
  std::string TakeWorkerError();

  // Returns RclResult object which indicates the final result.
  RclResult WaitForReadyCallbacks(rcl_wait_set_t* wait_set, int32_t time_out,
                                  WaitMode mode);

  // Calls the callback of the ready handle.
  void ExecuteReadyHandles();

  // Notifies the JS event loop of ready callbacks or worker errors.
  uv_async_t* async_;

  // Sub thread used to query the ready handles.
  uv_thread_t background_thread_;

  HandleManager* handle_manager_;
  Delegate* delegate_;
  rcl_context_t* context_;
  rcl_guard_condition_t interrupt_guard_condition_;
  int32_t time_out_;
  Napi::Env env_;

  std::atomic<ExecutorState> state_;

  // Shared state for worker-to-JS-thread dispatch.
  // The worker waits on js_dispatch_done_cv_ for JS dispatch completion or
  // stop, and for earlier callbacks to unwind before starting a new spin.
  // js_dispatch_mutex_ protects js_dispatch_pending_, callbacks_in_flight_,
  // and worker_error_, and coordinates lifecycle changes that wake the worker.
  std::mutex js_dispatch_mutex_;
  std::condition_variable js_dispatch_done_cv_;
  bool js_dispatch_pending_;
  std::size_t callbacks_in_flight_;
  std::string worker_error_;
};

}  // namespace rclnodejs

#endif  // SRC_EXECUTOR_H_
