/*
 * Copyright 2024 Bloomberg Finance LP
 *
 * 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 INCLUDED_BUILDBOXCASD_LOCALEXECUTIONINSTANCE_H
#define INCLUDED_BUILDBOXCASD_LOCALEXECUTIONINSTANCE_H

#include <buildboxcasd_executioninstance.h>
#include <buildboxcasd_localexecutionscheduler.h>

#include <buildboxcommon_connectionoptions.h>
#include <buildboxcommon_localexecutionclient.h>

#include <memory>
#include <string>

using namespace build::bazel::remote::execution::v2;
using namespace google::longrunning;

namespace buildboxcasd {

class LocalExecutionInstance final : public ExecutionInstance {
  public:
    explicit LocalExecutionInstance(
        const std::shared_ptr<LocalExecutionScheduler> &scheduler,
        const std::string &instanceName);

    ~LocalExecutionInstance() override;

    LocalExecutionInstance(const LocalExecutionInstance &) = delete;
    LocalExecutionInstance &operator=(const LocalExecutionInstance &) = delete;
    LocalExecutionInstance(LocalExecutionInstance &&) = delete;
    LocalExecutionInstance &operator=(LocalExecutionInstance &&) = delete;

    LocalExecutionInstance(const LocalExecutionInstance &other,
                           const std::string &instanceName);

    std::shared_ptr<ExecutionInstance>
    clone(const std::string &instanceName) override;

    grpc::Status Execute(ServerContext *ctx, const ExecuteRequest &request,
                         ServerWriterInterface<Operation> *writer) override;

    grpc::Status
    WaitExecution(ServerContext *ctx, const WaitExecutionRequest &request,
                  ServerWriterInterface<Operation> *writer) override;

    grpc::Status GetOperation(const GetOperationRequest &request,
                              Operation *response) override;

    grpc::Status CancelOperation(const CancelOperationRequest &request,
                                 google::protobuf::Empty *response) override;

    void stop() override;

  private:
    std::shared_ptr<LocalExecutionScheduler> d_scheduler;

    std::shared_ptr<buildboxcommon::LocalExecutionClient> d_execClient;

    std::string d_casInstanceNameForRunner;
};

} // namespace buildboxcasd

#endif // INCLUDED_BUILDBOXCASD_LOCALEXECUTIONINSTANCE_H
